问题描述
我在许多最顶层的头文件中看到下面的宏:
I have seen below macro in many topmost header files:
#define NULL 0 // C++03
在所有代码中, NULL
和 0
可互换使用。如果我将它更改为。
In all over the code, NULL
and 0
are used interchangeably. If I change it to.
#define NULL nullptr // C++11
会产生不良的副作用吗?我可以想到唯一的(良好的)副作用,如下面的用法会变得不合理:
Will it cause any bad side effect ? I can think of the only (good) side effect as following usage will become ill-formed;
int i = NULL;
推荐答案
您不应该看到,标准库定义在 ; cstddef>
(和< stddef.h>
)。并且,根据标准,IIRC重新定义由标准头文件定义的名称将导致未定义的行为。因此,从纯粹的标准角度来看,你不应该这样做。
You shouldn't have seen that, the standard library defines it in <cstddef>
(and <stddef.h>
). And, IIRC, according to the standard, redefining names defined by standard header files results in undefined behaviour. So from a purely standardese viewpoint, you shouldn't do that.
无论什么原因他们的想法思想:
I've seen people do the following, for whatever reason their broken mind thought of:
struct X{
virtual void f() = NULL;
}
(与[错误地]:一样,将虚拟表指针设置为 NULL
)
(As in [incorrectly]: "set the virtual table pointer to NULL
")
只有在定义 NULL
as 0
,因为 = 0
是纯虚函数的有效标记(§9.2 [class.mem]
)。
This is only valid if NULL
is defined as 0
, because = 0
is the valid token for pure-virtual functions (§9.2 [class.mem]
).
也就是说, if NULL
正确使用作为空指针常量。
That said, if NULL
was correctly used as a null pointer constant, then nothing should break.
但是,请注意, ,这将改变:
However, beware that, even if seemingly used correctly, this will change:
void f(int){}
void f(char*){}
f(0); // calls f(int)
f(nullptr); // calls f(char*)
然而,如果是这种情况,无论如何。
However, if that was ever the case, it was almost certainly broken anyways.
这篇关于它是安全的#define NULL nullptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!