nullptr 还是 NULL 0

  • 类型差异

    • NULL0

      #include <iostream>
      template <typename T>
      void show( T&& a) {
         a.error();
      }
      
      int main () {
         show(NULL);
      }
      
      • 输出

      D:\codes\cfile\Test\test.cpp: In instantiation of 'void show(T&&) [with T = long long int]':
      D:\codes\cfile\Test\test.cpp:8:14:   required from here
      D:\codes\cfile\Test\test.cpp:4:7: error: request for member 'error' in 'a', which is of non-class type 'long long int'
          a.error();
          ~~^~~~~
      [Finished in 328ms]
      
      • 这里NULLlong long int类型.

      • 不同编译器实现不同.

    • 问题

      • NULL0都是内置类型,当出现同时重载指针和内置类型时. 会出现错误匹配或者二义性.

    • 错误匹配

      #include <iostream>
      
      void show(long long int) {
         std::cout << __LINE__ << std::endl;
      }
      
      void show(void *) {
         std::cout << __LINE__ << std::endl;
      }
      
      
      int main () {
         show(NULL);
      }
      
    • 二义性

      #include <iostream>
      
      void show(bool) {
         std::cout << __LINE__ << std::endl;
      }
      
      void show(void *) {
         std::cout << __LINE__ << std::endl;
      }
      
      
      int main () {
         show(NULL);
      }
      
    • 小结

      • nullptr是关键字.不需要include

      • nullptr有自己的类型,不会和普通类型出现二义性.

      • nullptr可以转化为任意类型的指针.

      • nullptr有编译器支持,C++11新特性.

  • 好处

    • 可读性

      #include <iostream>
      
      void* show() {
         return nullptr;
      }
      
      int main () {
         auto s = show();
         if (0 != s) {
         }
         if (NULL != s) {
         }
         if (nullptr != s) {
         }
      }
      
      • nullptr是后面的主流.

      • NULLnullptr一起有点混.

      • 0都不知道返回的是什么类型.

  • 模板

    • 分析

      • 前面介绍了NULL,0当作空指针,间接隐式转换还可以,但是通过模板就会变回原形.

      • 变回原型就不匹配,会出现警告之类的.

    • 隐式匹配

      #include <iostream>
      
      void show(void*) {
      
      }
      
      int main () {
         show(0);
         show(NULL);
      }
      
      • 关键是还不能出现自身类型的重载,出现了就可能出错.

    • 模板现原形

      #include <iostream>
      void cool(void*) {
      
      }
      template <typename T>
      void show(T&&a) {
         cool(a);
      }
      
      int main () {
         show(nullptr);
         // show(0);
         // show(NULL);
      }
      
      • 直接报错.

  • 总结

    • 内置类型方便,安全.

    • 兼容性强.不推荐使用NULL,0;

  • 發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章