I’m wondering about what the C++ standard says about code like this:
int* ptr = NULL;
int& ref = *ptr;
int* ptr2 = &ref;
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.
Dereferencing a NULL pointer is undefined behavior.
In fact the standard calls this exact situation out in a note (8.3.2/4 “References”):
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
sizeofoperator, because the operand tosizeofisn’t actually evaluated (so the dereference never actually occurs).