我想知道 C++ 标准对这样的代码有何规定:
int* ptr = NULL;
int& ref = *ptr;
int* ptr2 = &ref;
实际上,结果是 ptr2
为 NULL,但我想知道,这只是一个实现细节还是标准中已明确定义?
在不同的情况下,对 NULL 指针的取消引用应该会导致崩溃,但在这里我取消引用它是为了获得一个由编译器作为指针实现的引用,因此实际上并没有对 NULL 进行实际的取消引用。
最佳答案
取消引用 NULL 指针是未定义的行为。
事实上,标准在注释(8.3.2/4“引用”)中指出了这种确切情况:
Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.
顺便说一句:有一次我知道 NULL 指针可以以明确定义的方式“取消引用”作为 sizeof
运算符的操作数,因为操作数sizeof
并未实际评估(因此取消引用从未实际发生)。
关于C++ 标准 : dereferencing NULL pointer to get a reference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2727834/