C++中 0 与 NULL 与 nullptr之间的关系,nullptr_t 的实现
2017-11-05 00:46
344 查看
C++中 0 与 NULL 与 nullptr之间的关系,nullptr_t 的实现
来源 http://blog.csdn.net/Virtual_Func/article/details/49756913
参考了网上各种资料,理清楚了 0 与 NULL 以及 nullptr 的关系。
1. 从本质上
1) 0是int型的字面值常量
2) NULL 是预处理变量,定义在 cstdlib 中,其值是0
3) nullptr 是 nullptr_t 类型的字面值。
2. cstdlib 中 NULL 的定义
- #ifdef __cplusplus
- #define NULL 0
- #else
- #define NULL ((void *)0)
- #endif
之所以这样定义的原因,是因为在C语言中,允许 void* 类型隐式转换为任意指针类型,而C++中不允许这样的强制类型转换,但是可以为任意类型的指针赋0值,因此,在C++中将NULL 定义为0
3. 0 比 NULL 好
在网上的资料中,均是一致认为 0 比 NULL 好,因为很多可能会出错的时候,使用 0 更直观,如:
- void test(int i){ cout << "in int" << endl; }
- void test(int * i){ cout << "in int *" << endl; }
- int main()
- {
- test(0); //输出 in int
- test(NULL); //输出 in int
- }
此时,两个函数调用均会调用参数为 int 的 test,使用 0 调动的版本看起来更加直观,因为 0 本身是一个 int 类型的字面值常量,而会潜意识的认为 NULL 应该是一个指针类型,不利于查错
4. nullptr 比 0 更好
nullptr 是 nullptr_t 类型的常量,而该类型定义了转到任意指针类型的转换操作符,同时不允许该类型的对象转换到非指针类型,在上面的调用例子中,使用 nullptr,将会调用第二个函数,输出 “in int*”,因为 nullptr被转换为了int * ,符合我们通常的理解。对于nullptr_t 的类型可以定义如下:
- class nullptr_t
- {
- public:
- template<class T>
- inline operator T*() const //定义类型转换操作符,使nullptr_t 可转为任意非类成员指针类型
- { return 0; }
- //重载类型转换操作符,使 nullptr_t 可以转换为类 C 中任意的指针类型(数据成员指针/函数成员指针)
- //对类中数据成员的指针,T 将被推导为数据成员的类型 eg: int (X::*); 此时 T 为 int,C 为 X
- //对类中函数成员的指针,T 将被推导为函数成员的类型 eg: int (X::*)(int); 此时T 等效于: typedef int (T)(int)
- template<class C, class T>
- inline operator T C::*() const
- { return 0; }
- private:
- void operator&() const;
- };
- const null_ptr nullptr = {}
相关文章推荐
- C++中 0 与 NULL 与 nullptr之间的关系,nullptr_t 的实现
- C++11中0与 NULL与nullptr之间的关系
- 通过C++实现判断点与多边形的关系和两点之间的距离
- 【收集】C++ 中实现has-a关系
- 编译原理(七) 算符优先分析法(构造算符优先关系表算法及C++实现)
- c++和java之间的关系
- 抽象类与接口之间的继承和实现关系
- C++ 接口与实现分离技术---如何将文件间的编译关系降至最低
- 接口、抽象类、继承、实现的定义及它们之间的关系
- C++中类之间的关系
- C++实现——任意进制之间的转换
- UML中类之间的关系---依赖、关联、继承(泛化)、实现、组合、聚合
- 泛型编程、STL的概念、STL模板思想及其六大组件的关系,以及泛型编程(GP)、STL、面向对象编程(OOP)、C++之间的关系
- 在Delphi与C++之间实现函数与对象共享
- 用C++实现void reverse(char* str)函数,即反转一个null结尾的字符串.
- UML图中类之间的关系:依赖,泛化,关联,聚合,组合,实现
- C/C++中的NULL与nullptr
- 铁路列车之间的通信协议(MVB协议)分析软件C/C++实现(一) 文件预处理
- C++学习笔记之NULL vs nullptr
- Zigbee网络架构+ZigBee的体系结构+理解zigbee节点的实现的案例+“51单片机” 和 “zigbee” 、 “cc2530芯片” 之间的关系+芯片cc2530