C++ Casting std::shared_ptr pointers


Example

It is not possible to directly use static_cast, const_cast, dynamic_cast and reinterpret_cast on std::shared_ptr to retrieve a pointer sharing ownership with the pointer being passed as argument. Instead, the functions std::static_pointer_cast, std::const_pointer_cast, std::dynamic_pointer_cast and std::reinterpret_pointer_cast should be used:

struct Base { virtual ~Base() noexcept {}; };
struct Derived: Base {};
auto derivedPtr(std::make_shared<Derived>());
auto basePtr(std::static_pointer_cast<Base>(derivedPtr));
auto constBasePtr(std::const_pointer_cast<Base const>(basePtr));
auto constDerivedPtr(std::dynamic_pointer_cast<Derived const>(constBasePtr));

Note that std::reinterpret_pointer_cast is not available in C++11 and C++14, as it was only proposed by N3920 and adopted into Library Fundamentals TS in February 2014. However, it can be implemented as follows:

template <typename To, typename From>
inline std::shared_ptr<To> reinterpret_pointer_cast(
    std::shared_ptr<From> const & ptr) noexcept
{ return std::shared_ptr<To>(ptr, reinterpret_cast<To *>(ptr.get())); }