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
Using the shared_ptr aliasing constructor, a variation of ecatmur's answer can be derived:
#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::shared_ptr(
virtual_enable_shared_from_this_base::shared_from_this(),
static_cast(this));
}
std::shared_ptr shared_from_this() const {
return std::shared_ptr(
virtual_enable_shared_from_this_base::shared_from_this(),
static_cast(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();
}
I expect this version to be faster in many circumstances, since it avoids a costly dynamic cast. However, as usual, only becnhmarks have the final word. Also, I have added the const variation.