I have an object (Z) which derives from two other objects (A and B).
A and B both derive from enable_shared_from_this<>, respectively enable
Yes, as per bad weak pointer when base and derived class both inherit from boost::enable_shared_from_this the solution is to use virtual inheritance. Here's an implementation for the C++11 standard shared_ptr (not Boost):
#include
struct virtual_enable_shared_from_this_base:
std::enable_shared_from_this {
virtual ~virtual_enable_shared_from_this_base() {}
};
template
struct virtual_enable_shared_from_this:
virtual virtual_enable_shared_from_this_base {
std::shared_ptr shared_from_this() {
return std::dynamic_pointer_cast(
virtual_enable_shared_from_this_base::shared_from_this());
}
};
struct A: virtual_enable_shared_from_this {};
struct B: virtual_enable_shared_from_this {};
struct Z: A, B { };
int main() {
std::shared_ptr z = std::make_shared();
std::shared_ptr b = z->B::shared_from_this();
}
This isn't part of the default implementation, probably because of the overhead of virtual inheritance.