gpt4 book ai didi

c++ - 生命终结规则的差异?

转载 作者:IT老高 更新时间:2023-10-28 12:37:32 25 4
gpt4 key购买 nike

https://en.cppreference.com/w/cpp/language/lifetimeNotes 部分有这段代码,在此转载:

struct A {
int* p;
~A() { std::cout << *p; } // if n outlives a, prints 123
};
void f() {
A a;
int n = 123; // if n does not outlive a, this is optimized out (dead store)
a.p = &n;
}

Notes 部分想要表达什么?

据我了解,代码是 UB(或者是它),因为很明显 n 不会超过 a

这是什么意思:

difference in the end of lifetime rules between non-class objects (end of storage duration) and class objects (reverse order of construction) matters

但它并没有说重要如何

我对这整个部分感到非常困惑。

最佳答案

这是 C++ 生命周期规则的一个奇怪方面。 [basic.life]/1 tells us对象的生命周期结束:

  • if T is a class type with a non-trivial destructor ([class.dtor]), the destructor call starts, or
  • the storage which the object occupies is released, or is reused by an object that is not nested within o ([intro.object]).

添加了重点。 int 不是“具有非平凡析构函数的类类型”,因此它的生命周期仅在其占用的存储空间被释放时结束。相比之下,A 是具有非平凡析构函数的类类型”,因此它的生命周期在析构函数被调用时结束。

根据 [basic.stc.auto]/1,在范围退出时释放范围的存储空间:

The storage for [variables with automatic storage duration] lasts until the block in which they are created exits.

但是根据[stmt.jump]/2自动变量被销毁:

On exit from a scope (however accomplished), objects with automatic storage duration that have been constructed in that scope are destroyed in the reverse order of their construction.

注意指定了销毁顺序,但没有指定自动存储释放的顺序。这意味着实现可以在每个变量被销毁后立即释放存储空间,或者稍后一次性释放,或者以其他任意顺序释放。

现在,它使用单数存储(“存储用于...持续”)而不是单独讨论每个变量的事实可能表明其意图是一次性释放整个存储那个范围。但标准中没有明确说明这一点。因此,只要变量在其存储被释放之前被销毁,任何销毁与释放的顺序似乎都是合法的。

这意味着代码完全有可能工作,na 生命周期长。但不确定它是否确实有效。

关于c++ - 生命终结规则的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53785791/

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