我的类继承自多个基类,其中之一是 std::enable_shared_from_this
.必须是第一垒吗?
假设以下示例代码:
struct A { ~A(); };
struct B { ~B(); };
struct C : A, B, std::enable_shared_from_this<C> {};
std::make_shared<C>();
当
~A()
和 ~B()
运行,我可以确定存储在哪里C
住过吗?
最佳答案
When ~A() and ~B() run, can I be sure that the storage where C lived is still present?
不,基类的顺序无关紧要。即使使用(或不使用) enable_shared_from_this 也是无关紧要的。
当一个 C 对象被销毁时(无论如何发生),
~C()
将在 ~A()
之前调用和 ~B()
,因为这是基础析构函数的工作方式。如果您尝试在基析构函数和其中的访问字段中“重建”C 对象,则这些字段将已经被销毁,因此您将获得未定义的行为。
关于c++ - enable_shared_from_this 必须是第一个基类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60695191/