c++11 - Use of enable_shared_from_this with multiple inheritance -
bi using enable_shared_from_this
in code, , not sure if usage correct. code:
class a: public std::enable_shared_from_this<a> { public: void foo1() { auto ptr = shared_from_this(); } }; class b:public std::enable_shared_from_this<b> { public: void foo2() { auto ptr = shared_from_this(); } }; class c:public std::enable_shared_from_this<c> { public: void foo3() { auto ptr = shared_from_this(); } }; class d: public a, public b, public c { public: void foo() { auto ptr = a::shared_from_this(); } };
are these usage of make_shared_from_this()
correct, assuming being called through shared_ptr
of d?
indeed doing wrong. if have simple inheritance, inherit enable_shared_from this
in base class, , derived class free. (of course you'll need downcast result)
if have multiple inheritance (like seems), must use trick described here , here :
/* trick allow multiple inheritance of objects * inheriting shared_from_this. * cf. https://stackoverflow.com/a/12793989/587407 */ /* first common base class * of course, 1 should virtually inherit it. */ class multipleinheritableenablesharedfromthis: public std::enable_shared_from_this<multipleinheritableenablesharedfromthis> { public: virtual ~multipleinheritableenablesharedfromthis() {} }; template <class t> class inheritable_enable_shared_from_this : virtual public multipleinheritableenablesharedfromthis { public: std::shared_ptr<t> shared_from_this() { return std::dynamic_pointer_cast<t>(multipleinheritableenablesharedfromthis::shared_from_this()); } /* utility method downcast. * useful when child doesn't inherit directly enable_shared_from_this * wants use feature. */ template <class down> std::shared_ptr<down> downcasted_shared_from_this() { return std::dynamic_pointer_cast<down>(multipleinheritableenablesharedfromthis::shared_from_this()); } };
then code becomes :
class a: public inheritable_enable_shared_from_this<a> { public: void foo1() { auto ptr = shared_from_this(); } }; class b: public inheritable_enable_shared_from_this<b> { public: void foo2() { auto ptr = shared_from_this(); } }; class c: public inheritable_enable_shared_from_this<c> { public: void foo3() { auto ptr = shared_from_this(); } }; class d: public a, public b, public c { public: void foo() { auto ptr = a::downcasted_shared_from_this<d>(); } };
Comments
Post a Comment