gpt4 book ai didi

c++ - 其中哪一个会创建一个空指针?

转载 作者:IT老高 更新时间:2023-10-28 22:33:49 28 4
gpt4 key购买 nike

标准说取消引用空指针会导致未定义的行为。但什么是“空指针”?在下面的代码中,我们称之为“空指针”:

struct X
{
static X* get() { return reinterpret_cast<X*>(1); }
void f() { }
};

int main()
{
X* x = 0;
(*x).f(); // the null pointer? (1)

x = X::get();
(*x).f(); // the null pointer? (2)

x = reinterpret_cast<X*>( X::get() - X::get() );
(*x).f(); // the null pointer? (3)

(*(X*)0).f(); // I think that this the only null pointer here (4)
}

我的想法是空指针的取消引用只发生在最后一种情况下。我对吗?根据 C++ 标准,编译时空指针和运行时有区别吗?

最佳答案

只有第一个和最后一个是空指针。其他是 reinterpret_cast 的结果,因此对实现定义的指针值进行操作。他们的行为是否未定义取决于您转换到的地址是否有对象。

关于c++ - 其中哪一个会创建一个空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2511921/

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