悬空引用和未定义行为
假设一个悬空引用x
.只是写是未定义的行为
Assume a dangling reference x
. Is it undefined behavior to just write
&x;
甚至
x;
?
推荐答案
首先,非常有趣的问题.
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:未定义的行为
本国际标准没有要求的行为[注意:当本国际标准省略任何明确的定义时,可能会出现未定义的行为行为或当程序使用错误的构造或错误的数据时....]
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:
- 如果标准没有描述某种情况下的行为,则行为未定义.
- 该标准仅描述对象在其生命周期内的行为,以及在生命周期开始/结束附近的一些特殊情况.这些都不适用于我们的悬空参考.
- 因此,以任何方式使用danling引用都没有标准规定的行为,因此行为未定义.
相关文章