转载地址:http://www.stroustrup.com/bs_faq2.html#null

为什么应该使用nullptr呢,以下是c++之父的解释:

1down vote

Here is Bjarne Stroustrup's wordings,

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

即:

在C++中,NULL就是0(#define NULL 0)(在C中,NULL被定义为0或void*),有时人们认为NULL和整数0是不同的,或者NULL不是个整数。

这就可能给程序带来二义性。比如以下重载函数:

void f(int)  ----------->f(0)

void f(const char *)----------->f(NULL) == f(0)

当使用f(NULL)时,你认为程序应该调用f(const char *),但现实情况中,f(NULL)调用的是f(int),这样就会出现二义性了。正确的调用方法应该是:f(nullptr);

而nullptr是一个指针类型( std::nullptr_t ),当你想命名一个空指针时,就用nullptr。