如果初始化程序不正确,为什么会这样?
Why is this if with initializer not true?
int* get(){return nullptr;}
int main()
{
if(auto p = get(); (*p) != 1231231233)
{
std::cout << "NO"; // not printed
}
else
{
std::cout << "we should be here" << std::endl;;
}
}
为什么这里没有NO
打印出来,因为根据standard,init-statement没有检查为true,访问*p
应该是 UB,我们应该得到 true
?。我不解:
LIVE
您在 if
子句中取消引用 nullptr,这是未定义的行为。基本上允许编译器对该段代码做任何它想做的事情。您不能对执行 (*p)
时会发生什么做出任何假设。
int* get(){return nullptr;}
int main()
{
if(auto p = get(); (*p) != 1231231233)
{
std::cout << "NO"; // not printed
}
else
{
std::cout << "we should be here" << std::endl;;
}
}
为什么这里没有NO
打印出来,因为根据standard,init-statement没有检查为true,访问*p
应该是 UB,我们应该得到 true
?。我不解:
LIVE
您在 if
子句中取消引用 nullptr,这是未定义的行为。基本上允许编译器对该段代码做任何它想做的事情。您不能对执行 (*p)
时会发生什么做出任何假设。