22 Oct
2003
22 Oct
'03
12:11 p.m.
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.