从第三方定义的类继承时shared_from_this

shared_from_this when inheriting from class defined by third party

本文关键字:shared from this 继承 第三方 定义      更新时间:2023-10-16

我在尝试研究我的问题时阅读了许多关于堆栈溢出的文章,内容涉及shared_from_this、bad_weak_ptr异常和多重继承。他们都建议你从enable_shared_from_this继承一个基类,然后从中派生。那么,当您必须派生的类来自您无法编辑的第三方库时,该怎么办?

例:

#include <iostream>
#include <memory>
class ThirdPartyClass
{
public:
ThirdPartyClass() {}
ThirdPartyClass(const ThirdPartyClass &) = delete;
virtual ~ThirdPartyClass() {};
};
class A : public ThirdPartyClass, std::enable_shared_from_this<A>
{
public:
A():ThirdPartyClass(){}
virtual ~A(){}
void Foo();
};
void DoStuff(std::shared_ptr<A> ptr)
{
std::cout << "Good job if you made it this far!" << std::endl;
}
void A::Foo()
{
DoStuff(shared_from_this());    // throws here
}
int main() {
std::shared_ptr<A> a = std::make_shared<A>();
a->Foo();
return 0;
}

您收到错误是因为您不是从enable_shared_from_thisshared_ptr的公共继承,并且make_shared无法检测到对象需要此类支持。不是因为从第三方类继承。

因此,要修复仅作为公共继承:

class A : public ThirdPartyClass, public std::enable_shared_from_this<A>