I have a class B which inherits from A which in turn derives from enabled_shared_from_this
. Now, I want to get a shared pointer to B from an instance of B. shared_from_this
will return shared_ptr<A>
, not shared_ptr<B>
. Should I use boost::static_pointer_cast
here? Or is there a better way?
views:
95answers:
2
+2
Q:
Getting a shared pointer to a derived class when base class inherits from enable_shared_from_this
+1
A:
I think in this case more preferable to use boost::dynamic_pointer_cast;
boost::shared_ptr<B> b = boost::dynamic_pointer_cast<B>(shared_from_this());
Sergey Teplyakov
2010-03-15 20:41:53
Why take the performance hit? I know this at compile time.
Nikhil
2010-03-15 21:09:42
+1
A:
This seems to be a valid approach as the type is known at compile time.
Nikhil
2010-03-19 22:07:16