gpt4 book ai didi

c++ - 空指针等价于 int

转载 作者:太空狗 更新时间:2023-10-29 20:49:07 25 4
gpt4 key购买 nike

在“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 运算符来实现,它将使用 01 初始化变量:

int castPointer = (voidPointer != 0);

关于c++ - 空指针等价于 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1642763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com