空指针等价于int [英] null pointer equivalence to int
问题描述
在C ++编程语言中,Bjarne写道,空指针与整数零不同,但是0可以用作空指针的指针初始值。这是否意味着:
In "The C++ Programming Language", Bjarne writes that the null pointer is not the same as the integer zero, but instead 0 can be used as an pointer initializer for a null pointer. Does this mean that:
void * voidPointer = 0;
int zero = 0;
int castPointer = reinterpret_cast<int>(voidPointer);
assert(zero == castPointer) // this isn't necessarily true
推荐答案
是的,这意味着 castPointer
不一定为零,并且断言可能失败。因为当空指针常数为零时,某种类型的空指针不一定是所有位为零的地址。
Yes, that means that castPointer
isn't necessarily zero, and the assert may fail. Because while the null pointer constant is zero, the null pointer of some type is not necessarily an address with all bits zero.
reinterpret_cast
没有特殊规定在将空指针转换为int时产生零。你可以通过使用布尔运算符来实现,它将用 0
或 1
:
reinterpret_cast
has no special provisions to yield zero when casting a null pointer to int. You can achieve that by using boolean operators, which will initialize the variable with either 0
or 1
:
int castPointer = (voidPointer != 0);
这篇关于空指针等价于int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!