- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
https://en.cppreference.com/w/cpp/language/lifetime在 Notes 部分有这段代码,在此转载:
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.
注意指定了销毁顺序,但没有指定自动存储释放的顺序。这意味着实现可以在每个变量被销毁后立即释放存储空间,或者稍后一次性释放,或者以其他任意顺序释放。
现在,它使用单数存储(“存储用于...持续”)而不是单独讨论每个变量的事实可能表明其意图是一次性释放整个存储那个范围。但标准中没有明确说明这一点。因此,只要变量在其存储被释放之前被销毁,任何销毁与释放的顺序似乎都是合法的。
这意味着代码完全有可能工作,n
比 a
生命周期长。但不确定它是否确实有效。
关于c++ - 生命终结规则的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53785791/
我正在开发一个使用多个 turtle 的滚动游戏。玩家 turtle 根据按键命令在 Y 轴上移动。当危害和好处在 X 轴上移动时,然后循环并改变 Y 轴位置。我尝试定义一个名为 colliding(
我不明白为什么他们不接受这个作为解决方案,他们说这是一个错误的答案:- #include int main(void) { int val=0; printf("Input:- \n
我正在使用基于表单的身份验证。 我有一个注销链接,如下所示: 以及对应的注销方法: public String logout() { FacesContext.getCurren
在 IIS7 应用程序池中有一个设置 Idle-time out 默认是 20 分钟,其中说: Amount of time(in minutes) a worker process will rem
我是一名优秀的程序员,十分优秀!