C++ 标准:取消引用 NULL 指针以获取引用?

2021-12-13 00:00:00 reference pointers null c++

我想知道 C++ 标准对这样的代码是怎么说的:

I'm wondering about what the C++ standard says about code like this:

int* ptr = NULL;
int& ref = *ptr;
int* ptr2 = &ref;

在实践中,结果是 ptr2 为 NULL,但我想知道,这只是一个实现细节还是在标准中定义得很好?
在不同的情况下,取消引用 NULL 指针应该会导致崩溃,但在这里我取消引用它以获取由编译器作为指针实现的引用,因此实际上没有实际取消引用 NULL.

In practice the result is that ptr2 is NULL but I'm wondering, is this just an implementation detail or is this well defined in the standard?
Under different circumstances a dereferencing of a NULL pointer should result in a crash but here I'm dereferencing it to get a reference which is implemented by the compiler as a pointer so there's really no actual dereferencing of NULL.

推荐答案

取消引用 NULL 指针是未定义的行为.

Dereferencing a NULL pointer is undefined behavior.

事实上,标准在注释(8.3.2/4参考")中明确指出了这种情况:

In fact the standard calls this exact situation out in a note (8.3.2/4 "References"):

注意:特别是,在定义良好的程序中不能存在空引用,因为唯一的创建这样一个引用的方法是将它绑定到通过取消引用空指针获得的对象",这会导致未定义的行为.

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.

<小时>

顺便说一句:有一次我意识到可以以明确定义的方式取消引用"空指针是作为 sizeof 运算符的操作数,因为操作数sizeof 实际上并没有被评估(所以解引用从来没有真正发生过).


As an aside: The one time I'm aware of that a NULL pointer can be "dereferenced" in a well-defined way is as the operand to the sizeof operator, because the operand to sizeof isn't actually evaluated (so the dereference never actually occurs).

相关文章