Dangling references and undefined behavior

Supposing that x was initialized with a valid object, which was then destroyed, §3.8/6 applies:

Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways. For an object under construction or destruction, see 12.7. Otherwise, such a glvalue refers to allocated storage (3.7.4.2), and using the properties of the glvalue that do not depend on its value is well-defined. The program has undefined behavior if:

— an lvalue-to-rvalue conversion (4.1) is applied to such a glvalue,

— the glvalue is used to access a non-static data member or call a non-static member function of the
object, or

— the glvalue is bound to a reference to a virtual base class (8.5.3), or

— the glvalue is used as the operand of a dynamic_cast (5.2.7) or as the operand of typeid.

So, simply taking the address is well-defined, and (referring to the neighboring paragraphs) can even be productively used to create a new object in place of the old one.

As for not taking the address and just writing x, that really does absolutely nothing, and it is a proper subexpression of &x. So it’s also OK.

Leave a Comment