Dangling references and undefined behavior

前端 未结 3 1038
鱼传尺愫
鱼传尺愫 2020-12-03 08:14

Assume a dangling reference x. Is it undefined behavior to just write

&x;

or even

x;

?

3条回答
  •  日久生厌
    2020-12-03 08:46

    First off, very interesting question.

    I would say it is undefined behaviour, assuming "dangling reference" means "referred-to object's lifetime has ended and the storage the object occupied has been reused or released." I base my reasoning on the following standard rulings:

    3.8 §3:

    The properties ascribed to objects throughout this International Standard apply for a given object only during its lifetime. [ Note: In particular, before the lifetime of an object starts and after its lifetime ends there are significant restrictions on the use of the object, as described below ...]

    All the cases "as described below" refer to

    Before the lifetime of an object has started but after the storage which the object will occupy has been allocated38 or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released

    1.3.24: undefined behavior

    behavior for which this International Standard imposes no requirements [ Note: Undefined behavior may be expected when this International Standard omits any explicit definition of behavior or when a program uses an erroneous construct or erroneous data. ...]

    I apply the following train of thoughts to the above quotes:

    1. If the standard doesn't describe behaviour for a situation, the behvaiour is undefined.
    2. The standard only describes behvaiour for objects within their lifetime, and a few special cases near the start/end of their lifetime. None of these apply to our dangling reference.
    3. Therefore, using the danling reference in any way has no behaviour prescribed by the standard, hence the behaviour is undefined.

提交回复
热议问题