static_cast with boost::shared_ptr?

C++BoostShared PtrStatic Cast

C++ Problem Overview


What is the equivalent of a static_cast with boost::shared_ptr?

In other words, how do I have to rewrite the following

Base* b = new Derived();
Derived* d = static_cast<Derived*>(b);

when using shared_ptr?

boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = ???

C++ Solutions


Solution 1 - C++

Use boost::static_pointer_cast:

boost::shared_ptr<Base> b(new Derived());
boost::shared_ptr<Derived> d = boost::static_pointer_cast<Derived>(b);

Solution 2 - C++

There are three cast operators for smart pointers: static_pointer_cast, dynamic_pointer_cast, and const_pointer_cast. They are either in namespace boost (provided by <boost/shared_ptr.hpp>) or namespace std::tr1 (provided either by Boost or by your compiler's TR1 implementation).

Solution 3 - C++

As a comment: if Derived does in fact derive from Base, then you should use a dynamic_pointer_cast rather than static casts. The system will have a chance of detecting when/if your cast is not correct.

Solution 4 - C++

It is worth to mention that the there is difference in the number of casting operators provided by Boost and implementations of TR1.

The TR1 does not define the third operator const_pointer_cast()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFrankView Question on Stackoverflow
Solution 1 - C++FrankView Answer on Stackoverflow
Solution 2 - C++Michael KristofikView Answer on Stackoverflow
Solution 3 - C++David Rodríguez - dribeasView Answer on Stackoverflow
Solution 4 - C++mloskotView Answer on Stackoverflow