Dangling references and undefined behavior(悬空引用和未定义行为)
问题描述
假设一个悬空引用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引用都没有标准规定的行为,因此行为未定义.
这篇关于悬空引用和未定义行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:悬空引用和未定义行为
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
