Getting a generic pointer to a derived class when the base class inherits from enable_shared_from_this

I have a class B that inherits from A, which in turn comes from enabled_shared_from_this. Now I want to get a generic pointer to B from an instance of B. shared_from_thiswill return shared_ptr<A>, not shared_ptr<B>. Should I use boost::static_pointer_casthere? Or is there a better way?

+3
source share
2 answers

This seems like a valid approach since the type is known at compile time.

+1
source

I think in this case it is preferable to use boost :: dynamic_pointer_cast ;

boost::shared_ptr<B> b = boost::dynamic_pointer_cast<B>(shared_from_this());
+1
source

Source: https://habr.com/ru/post/1737044/


All Articles