我想知道 NULL
在 C++ 中是否保证为 0
,所以我搜索并发现了这些:
This回答指出:
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.
这似乎证实了 NULL
始终为 0。
但根据cppreference.com :
#define NULL /*implementation-defined*/
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)
这清楚地表明 NULL
是依赖于实现的。
This回答说:
0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:
f(int); f(foo *);
这再次暗示 NULL
是整数 0
,这可能会导致歧义
还有其他遇到的问答,但大多是C语言的,不是C++的。 This评论说:
And NULL is guaranteed to be 0
但同样,这是关于 C 的。
总而言之,NULL
在 C++ 中总是 0
吗? C呢?它(对于每个标准实现)是否与:
#define NULL 0
注意:这个问题不是关于空指针的问题,问题是C++中的NULL
是否保证是0
整数。它依赖于实现吗?
最佳答案
Is NULL guaranteed to be 0?
根据标准,NULL
是一个空指针常量(即字面量)。具体是哪一个,由实现定义。
在C++11之前,空指针常量是整型常量,其整型值等于0,所以0
或0l
等
从 C++11 开始,有一个新的空指针文字 nullptr
并且 NULL
可以定义为 nullptr
。 (因此,对 Bjarne 引述的字面解释已经过时了)。
在标准化之前:NULL
在 C 中可以定义为 (void*)0
。由于 C++ 是基于 C 的,所以很可能某些 C++ 方言预约会标准可能使用了该定义,但这样的定义不符合标准 C++。
为了完整起见:正如下面评论中链接的 SO 帖子中更详细的解释,空指针常量为 0 并不一定意味着空指针地址的值为 0(尽管地址为 0 是非常典型的) .
关于这个可以得出什么结论:
- 不要使用
NULL
来表示数字零(如果合适,请使用带有适当类型后缀的0
),也不要用来表示空终止符(使用>'\0'
). - 不要假设
NULL
解析为指针重载。 - 如果您的标准是 >= C++11,请不要使用
NULL
来表示空指针,而是使用nullptr
。在较旧的标准中,如果需要重载解析,可以使用(T*)NULL
或(T*)0
...也就是说可能很少有情况用指针重载整数很有意义。 - 考虑到在从 C 转换为 C++ 时定义可能不同,反之亦然。
- 不要将零位存储(或键入双关语)到指针中。这不能保证是空指针。
关于c++ - NULL 保证为 0 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54098794/