...imagine you have the following two function declarations:
void func(int n);
void func(char *s);
func( NULL ); // guess which function gets called?
Although it looks like the second function will be called--you are, after all, passing in what seems to be a pointer--it's really the first function that will be called! The trouble is that because NULL is 0, and 0 is an integer, the first version of func will be called instead. This is the kind of thing that, yes, doesn't happen all the time, but when it does happen, is extremely frustrating and confusing. If you didn't know the details of what is going on, it might well look like a compiler bug. A language feature that looks like a compiler bug is, well, not something you want.
Enter nullptr. In C++11, nullptr is a new keyword that can (and should!) be used to represent NULL pointers; in other words, wherever you were writing NULL before, you should use nullptr instead. It's no more clear to you, the programmer, (everyone knows what NULL means), but it's more explicit to the compiler, which will no longer see 0s everywhere being used to have special meaning when used as a pointer.
nullptr
在C++/CLI中还用于表示托管句柄的空引用。 - Mehrdad Afsharinullptr_t
是否保证只有一个成员nullptr
?如果一个函数返回nullptr_t
,那么编译器已经知道将返回哪个值,无论函数体是什么? - Aaron McDaidstd::nullptr_t
可以被实例化,但是所有的实例都与nullptr
相同,因为该类型被定义为typedef decltype(nullptr) nullptr_t
。我相信该类型存在的主要原因是为了函数可以进行重载,以便特别捕获nullptr
。示例可参见此处。 - Justin Time - Reinstate Monica