gpt4 book ai didi

c++ - 悬空引用和未定义行为

转载 作者:IT老高 更新时间:2023-10-28 23:18:26 28 4
gpt4 key购买 nike

假设一个悬空引用 x。只是写是未定义的行为吗

&x;

甚至

x;

?

最佳答案

首先,非常有趣的问题。

我会说这是未定义的行为,假设“悬空引用”意味着“被引用对象的生命周期已经结束,并且对象占用的存储已经被重用或释放。”我的推理基于以下标准裁决:

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 ...]

所有“如下所述”的情况均指

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. ...]

我将以下思路应用于上述引用:

  1. 如果标准未描述某种情况下的行为,则行为未定义。
  2. 该标准仅描述对象在其生命周期内的行为,以及接近其生命周期开始/结束的一些特殊情况。这些都不适用于我们的悬空引用。
  3. 因此,以任何方式使用 danling 引用都没有标准规定的行为,因此行为未定义。

关于c++ - 悬空引用和未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14730534/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com