Casting std::shared_ptr pointers

suggest change

Casting a std::shared_ptr object with static_cast, const_cast, dynamic_cast, or reinterpret_cast does not cast the stored pointer while keeping the same control block. Use std::static_pointer_cast, std::const_pointer_cast, std::dynamic_pointer_cast, and std::reinterpret_pointer_cast. An implicit conversion from std::shared_ptr<Derived> to std::shared_ptr<Base> does share ownership; static_pointer_cast is what you need for a static downcast:

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));

std::reinterpret_pointer_cast is not in C++11 or C++14. It was proposed by N3920, adopted into the Library Fundamentals TS in February 2014, and added to the standard library in C++17. Before that, 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())); }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents