问题描述
我想知道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 / 4References)中调用了这种情况:
In fact the standard calls this exact situation out in a note (8.3.2/4 "References"):
一次我知道一个NULL指针可以以一个明确定义的方式解引用作为 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).
这篇关于C ++标准:取消引用NULL指针以获取引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!