enable_shared_from_this and inheritance
I'm trying to use enable_shared_from_this with my classes that have an inheritance structure and a virtual function. I'd like to get a shared pointer to the descendant class B. I've attached 2 files. One compiles but errors at runtime, the other doesn;t compile. The first method uses makes both class A and B inherit from enable_shared_from_this. The 2nd method makes only the base class A inherit from enable_shared_from_this and tries to dynamic cast to shared_ptr<B>. -- sashan http://www.cs.auckland.ac.nz/~sgov008/ #include <iostream> #include <boost/enable_shared_from_this.hpp> using namespace std; using namespace boost; class A : public enable_shared_from_this<A> { public: A(){ cout << "A" << endl; } virtual void f() { shared_ptr<A> pA(shared_from_this());} }; class B : public A, public enable_shared_from_this<B> { public: B() { cout << "B" << endl;} virtual void f() { shared_ptr<B> pB(enable_shared_from_this<B>::shared_from_this()); } }; void main() { shared_ptr<A> a(new A); a->f(); shared_ptr<B> b(new B); b->f(); } #include <iostream> #include <boost/enable_shared_from_this.hpp> using namespace std; using namespace boost; class A : public enable_shared_from_this<A> { public: A(){ cout << "A" << endl; } virtual void f() { shared_ptr<A> pA(shared_from_this());} }; class B : public A { public: B() { cout << "B" << endl;} virtual void f() { shared_ptr<A> pA(shared_from_this()); shared_ptr<B> pB(dynamic_pointer_cast< shared_ptr<B> >(pA)); } }; void main() { shared_ptr<A> a(new A); a->f(); shared_ptr<B> b(new B); b->f(); }
virtual void f() { shared_ptr<A> pA(shared_from_this()); shared_ptr<B> pB(dynamic_pointer_cast< shared_ptr<B> >(pA)); } };
I just realized if I replaced shared_ptr<B> pB(dynamic_pointer_cast< shared_ptr<B> >(pA)); with shared_ptr<B> pB(dynamic_pointer_cast< B >(pA)); It will compile. What I'd like to know is if this is the way to do it. Initially I thought that the enanble_shared_from_this_0.cpp was the way to go, however it generates a run-time error.
sashan wrote:
virtual void f() { shared_ptr<A> pA(shared_from_this()); shared_ptr<B> pB(dynamic_pointer_cast< shared_ptr<B> >(pA)); } };
I just realized if I replaced
shared_ptr<B> pB(dynamic_pointer_cast< shared_ptr<B> >(pA));
with
shared_ptr<B> pB(dynamic_pointer_cast< B >(pA));
It will compile. What I'd like to know is if this is the way to do it.
In short, yes. The *_pointer_cast<> functions take the pointee type as a template parameter and return a pointer of the same category as the argument. You may want to consider making A an abstract base class with f() being pure virtual and only adding enable_shared_from_this<> to B. This isn't always possible, but when it is, it's often a clearer design.
participants (2)
-
Peter Dimov
-
sashan