gpt4 book ai didi

c++ - 重用存储是否开始新对象的生命周期?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:09:55 25 4
gpt4 key购买 nike

<分区>

#include <cstdlib>
struct B {
virtual void f();
void mutate();
virtual ~B();
};
struct D1 : B { void f(); };
struct D2 : B { void f(); };
void B::mutate() {
new (this) D2; // reuses storage — ends the lifetime of *this
f(); // undefined behavior - WHY????
... = this; // OK, this points to valid memory
}

我需要解释为什么 f() 调用有 UB? new (this) D2; 重用了存储,但它也调用了 D2 的构造函数,并开始了新对象的生命周期。在这种情况下,f() 等于 this -> f()就是我们调用了D2f()成员函数。谁知道为什么是UB?

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