c++ - enable_shared_from_this 必须是第一个基类吗?

标签 c++ c++11 inheritance multiple-inheritance enable-shared-from-this

我的类继承自多个基类,其中之一是 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/

相关文章:

c++ - 如何使用 STL 对数组进行 k-shuffle?

c++ - std::initializer_list 的实现

c++ - 从 vector 中删除元素时如何减小 vector 的大小?

C++:从模板参数继承类

python - 如何正确使用多重(重新)继承

C++ 编译错误只有一个候选函数

c++ - "Expression: vector iterator not deferencable"运行时错误

c++ - clang 根据其重载之一拒绝带有尾随 decltype 返回类型的模板调用是否正确?

c++ - constexpr 和 RTTI

C# 继承 : change field data type and value in derived class