I have a base class which derives from boost::enable_shared_from_this, and then another class which derives from both the base class and boost::enable_shared_from_this:
You shouldn't inherit from enable_shared_from_this
more than once in a given inheritance chain.
In this case, you can leave the base class A
inheriting from enable_shared_from_this
, and have the derived class B
return a shared_ptr
and then static_pointer_cast it to shared_ptr
.
Or as Omnifarious pointed out, you could have a function in B
which does this for you. Although, rather than overloading shared_from_this()
I would favour explicitly-named functions to minimise surprises for clients of the class:
#include
#include
using boost::shared_ptr;
class A : public boost::enable_shared_from_this { };
class B : public A {
public:
using enable_shared_from_this::shared_from_this;
shared_ptr shared_B_from_this() {
return boost::static_pointer_cast(shared_from_this());
}
shared_ptr shared_B_from_this() const {
return boost::static_pointer_cast(shared_from_this());
}
};
int main() {
shared_ptr b = shared_ptr(new B);
shared_ptr b1 = boost::static_pointer_cast(b->shared_from_this());
shared_ptr b2 = b->shared_B_from_this();
return 0;
}