nullptr VS NULL
NULL
NULL is 0 (zero) i.e. integer constant zero with C-style typecast to void*,
NULL 是 0(零),即整数常量零,在C 风格类型转换为 void*
,
nullptr
while nullptr is prvalue of type nullptr_t, which is an integer literal that evaluates to zero.
而 nullptr 是 nullptr_t
类型的纯右值,它是一个计算为零的整数文字。
C++ requires that macro NULL be defined as an integral constant expression, having the value of 0.
C++ 要求将宏 NULL 定义为整数常量表达式,其值为 0。
So, unlike in C, NULL cannot be defined as (void *)0
in the C++ standard library.
因此,与 C 不同,NULL 在 C++ 标准库中不能定义为(void *)0
。
C++:
char *str = NULL; // Implicit conversion from void * to char *
int i = NULL; // OK, but `i` is not pointer type
另附:
The macro NULL is an implementation-defined null pointer constant, which may be
an integer constant expression with the value 0
an integer constant expression with the value 0 cast to the type void*
A null pointer constant may be converted to any pointer type; such conversion results in the null pointer value of that type.
===============================================================
The macro NULL is an implementation-defined null pointer constant, which may be
an integral constant expression rvalue of integer type that evaluates to zero(until C++11)
an integer literal with value zero, or a prvalue of type std::nullptr_t(since C++11)
A null pointer constant may be implicitly converted to any pointer and pointer to member type; such conversion results in the null pointer value of that type. If a null pointer constant has integer type, it may be converted to a prvalue of type std::nullptr_t.
===============================================================
所以,总结一下就是NULL在C语言中表示空指针,赋值时发生了隐式类型转换,void指针转换成相应类型的指针;而在C++中,C++是强类型语言,空指针不能隐式转换成其他类型的指针,NULL只表示0,一般表示NULL等同于nullptr,而当遇到函数重载情况就会出现问题。
综上所述,在C中正常的使用NULL,而在C++中就全部使用nullptr替换NULL吧。