空指针与 int 等价
Bjarne 在《C++ 编程语言》中写道,空指针与整数零不同,但 0 可以用作空指针的指针初始值设定项。这是否意味着:
void * voidPointer = 0;
int zero = 0;
int castPointer = reinterpret_cast<int>(voidPointer);
assert(zero == castPointer) // this isn't necessarily true
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这意味着
castPointer
不一定为零,并且断言可能会失败。因为虽然空指针常量为零,但某些类型的空指针不一定是所有位都为零的地址。在将空指针转换为 int 时,reinterpret_cast 没有特殊的规定来产生零。您可以通过使用布尔运算符来实现此目的,该运算符将使用
0
或1
初始化变量: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
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 either0
or1
: