在c++的早期,当它被固定在C的顶部时,你不能使用NULL,因为它被定义为(void*)0。你不能将NULL赋值给除void*以外的任何指针,这使得它有点无用。在那些日子里,人们接受使用0(零)作为空指针。
直到今天,我仍然使用0作为空指针,但我周围的人坚持使用null。我个人认为给一个现有的值命名(NULL)没有任何好处-因为我也喜欢将指针作为真值测试:
if (p && !q)
do_something();
那么使用0就更有意义了(就像如果你使用NULL,你不能在逻辑上使用p && !q -你需要显式地与NULL进行比较,除非你假设NULL为零,在这种情况下为什么要使用NULL)。
是否有任何客观的原因让人们更喜欢0而不是NULL(反之亦然),或者这只是个人偏好?
编辑:我应该补充(最初的意思是说),对于RAII和异常,我很少使用零/NULL指针,但有时你仍然需要它们。
曾经有人告诉我……我将把NULL重新定义为69。从那以后,我不再使用它:P
它使您的代码非常脆弱。
编辑:
标准中并非所有内容都是完美的。宏NULL是一个实现定义的c++空指针常量,与C NULL宏不完全兼容,除了类型隐藏隐式转换它在一个无用的和容易出错的工具。
NULL不是一个空指针,而是一个O/OL文字。
告诉我下一个例子不会让人困惑:
void foo(char *);
void foo(int);
foo(NULL); // calls int version instead of pointer version!
是不是因为这一切,在新标准中出现了std::nullptr_t
如果你不想等待新标准的出台,想要使用nullptr,至少要使用一个像Meyers建议的那样像样的nullptr(参见jonh comment)。
下面是Stroustrup对此的看法:c++风格和技术常见问题解答
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.
也就是说,不要为小事烦恼。