Reputation: 4010
I've read many posts on stack-overflow about shared_from_this, bad_weak_ptr exceptions, and multiple inheritance while trying to research my problem. All of them propose you inherit a base class from enable_shared_from_this, and then derive from that. Well, what does one do when the class you have to derive from is a coming from a third party library that you cannot edit?
Example:
#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;
}
Upvotes: 1
Views: 157
Reputation: 2973
You get the error because you are not public inheriting from enable_shared_from_this
and shared_ptr
and make_shared
cannot detect that the object requires such support. Not because of inheritance from third party class.
So, to fix just inherit as public:
class A : public ThirdPartyClass, public std::enable_shared_from_this<A>
Upvotes: 1