gpt4 book ai didi

c++ - 这是一个 nullptr 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:47 25 4
gpt4 key购买 nike

阅读 this问答,我认为 p 不应该是 nullptr,即使 x0。我理解的对吗?

int main()
{
int x = 0;

std::cin >> x; // Enter `0`

void *p = (void *)x; // or: void *p = reinterpret_cast<void*>(x);


if (!p)
std::cout << "p is nullptr" << std::endl;
}

在标准输入中输入 0 后,消息 p is nullptr 将显示在我的 GCC 中。根据link ,它不应计算为 nullptr,但结果并不如我所料。

代码是未定义的行为吗?或未指定的结果?为什么它求值为 nullptr

最佳答案

来自 C++11 5.2.10/5 Reinterpret cast [expr.reinterpret.cast](强调已添加):

A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of suffcient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined.

来自 5.2.10/4 的相关位:

A value of type std::nullptr_t can be converted to an integral type; the conversion has the same meaning and validity as a conversion of (void*)0 to the integral type. [ Note: A reinterpret_cast cannot be used to convert a value of any type to the type std::nullptr_t. —end note ]

关于c++ - 这是一个 nullptr 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23638947/

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