在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指针,但有时你仍然需要它们。


当前回答

下面是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.

也就是说,不要为小事烦恼。

其他回答

我通常用0。我不喜欢宏,而且不能保证您使用的某些第三方头文件不会将NULL重新定义为一些奇怪的东西。

你可以使用一个由Scott Meyers和其他人提出的nullptr对象,直到c++获得一个nullptr关键字:

const // It is a const object...
class nullptr_t 
{
public:
    template<class T>
    operator T*() const // convertible to any type of null non-member pointer...
    { return 0; }

    template<class C, class T>
    operator T C::*() const   // or any type of null member pointer...
    { return 0; }

private:
    void operator&() const;  // Can't take address of nullptr

} nullptr = {};

谷歌"nullptr"获取更多信息。

下面是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.

也就是说,不要为小事烦恼。

我想说,历史已经证明了这一点,那些主张使用0(零)的人是错误的(包括Bjarne Stroustrup)。支持0的理由主要是审美和“个人偏好”。

c++ 11创建后,使用新的nullptr类型,一些编译器开始抱怨(使用默认形参)将0传递给带有指针参数的函数,因为0不是指针。

如果代码是使用NULL编写的,那么可以通过代码库执行简单的搜索和替换,使其成为nullptr。如果您被使用0作为指针编写的代码所困扰,那么更新它将变得更加乏味。

如果你现在必须为c++ 03标准编写新代码(并且不能使用nullptr),你真的应该只使用NULL。这将使您将来更容易更新。

我认为标准保证NULL == 0,所以你可以做任何一件事。我更喜欢NULL,因为它记录了您的意图。

我曾经在一台机器上工作,其中0是一个有效地址,NULL被定义为一个特殊的八进制值。在该机器上(0 != NULL),因此代码如

char *p;

...

if (p) { ... }

不会如你所愿。你必须写

if (p != NULL) { ... }

虽然我相信现在大多数编译器都将NULL定义为0,但我仍然记得那些年前的教训:NULL不一定是0。