Search code examples
c++castingc++17

What is `std::reinterpret_pointer_cast` and when should it be used?


Link to reference: std::reinterpret_pointer_cast

Should this be used when weak_ptr or shared_ptr are involved (Why? Always? Sometimes?)


Solution

  • Like all the other std::*_pointer_cast functions, this allows you to cast between different pointer types wrapped in std::shared_ptr as if the corresponding raw pointer was cast, but while retaining shared ownership.

    So std::reinterpret_pointer_cast<T>(ptr) is (mostly) the same as std::shared_ptr<T>(reinterpret_cast<T*>(ptr.get())), with the important difference that the latter would cause the cast raw pointer to be stored in a new shared pointer which is not associated with the original one, so that the managed object will be double-deleted once by the original shared pointer complex and once by the new one (and the latter potentially with the wrong type).

    Instead std::reinterpret_pointer_cast<T>(ptr) is (mostly) equivalent to std::shared_ptr<T>(ptr, reinterpret_cast<T*>(ptr.get())), which uses the so-called aliasing constructor of std::shared_ptr. It allows one to obtain a std::shared_ptr referencing any pointer (the second argument), while still having ownership associated with the original shared_ptr (first argument).

    So you should use std::reinterpret_pointer_cast if you have a std::shared_ptr and you would have used reinterpret_cast if it had been a raw pointer instead.

    Since use cases for reinterpret_cast are rare, you will be much more likely to use std::dynamic_pointer_cast or std::static_pointer_cast, which are useful for down- and side-cast in class hierarchies.