There is no problem deriving from a class which inherits from std::enable_shared_from_this
. For example this code will work:
#include <memory>
class A : public std::enable_shared_from_this<A> {
public:
void bar()
{
auto a = shared_from_this();
}
};
class B : public A {
public:
void foo()
{
auto a = shared_from_this();
}
};
int main()
{
auto b = std::make_shared<B>();
b->foo();
b->bar();
}
Conversely deriving from std::enable_shared_from_this
multiple times can lead to issues:
#include <memory>
class A : public std::enable_shared_from_this<A> {
public:
void bar()
{
auto a = shared_from_this();
}
};
class B : public A, public std::enable_shared_from_this<B> {
public:
void foo()
{
auto a = std::enable_shared_from_this<B>::shared_from_this();
}
};
int main()
{
auto b = std::make_shared<B>();
b->foo();
b->bar();
}
Now shared_from_this
is ambiguous in B
so we have to explicitly qualify it when we use it but worse it'll stop working properly: bad weak pointer when base and derived class both inherit from boost::enable_shared_from_this
Note that you should add a virtual destructor to A
to avoid potential pitfalls when destructing objects (though shared_ptr
, when used correctly, does workaround this issue)