在“The C++ Programming Language”中,Bjarne 写道,空指针与整数零不同,而是 0 可以用作空指针的指针初始值设定项。这是否意味着:
void * voidPointer = 0;
int zero = 0;
int castPointer = reinterpret_cast<int>(voidPointer);
assert(zero == castPointer) // this isn't necessarily true
最佳答案
是的,这意味着 castPointer
不一定为零,断言可能会失败。因为当空指针常量 为零时,某些类型的空指针 不一定是所有位都为零的地址。
reinterpret_cast
没有特别规定在将空指针转换为 int 时产生零。您可以通过使用 bool 运算符来实现,它将使用 0
或 1
初始化变量:
int castPointer = (voidPointer != 0);
关于c++ - 空指针等价于 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1642763/