std::static...ointer_cast,(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

✨ std::static_pointer_cast, std::dynamic_pointer_cast, std::const_pointer_cast ✨

okay so bestie, this is the C++ Standard Libary page for the pointer-cast girlies β€” πŸ’… we're talking std::static_pointer_cast,std::dynamic_pointer_cast,std::const_pointer_cast, and their chaotic little sibling reinterpret_pointer_cast. All four of them are literally just "make me a new shared_ptr but with a different type, please and thank you." πŸŽ€


🌸 NAME 🌸

std::static_pointer_cast, std::dynamic_pointer_cast, std::const_pointer_cast, β€” yeah that's the whole name, the page title got a little truncated, we move πŸ’€


πŸ¦‹ Synopsis πŸ¦‹

Defined in header <memory> β€” don't forget it, iykyk 🫢

template< class T, class U >
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>&
(1) (since C++11)
r ) noexcept;
template< class T, class U >
std::shared_ptr<T> static_pointer_cast( std::shared_ptr<U>&& r )
(2) (since C++20)
noexcept;
template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>&
(3) (since C++11)
r ) noexcept;
template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( std::shared_ptr<U>&& r )
(4) (since C++20)
noexcept;
template< class T, class U >
std::shared_ptr<T> const_pointer_cast( const std::shared_ptr<U>& r
(5) (since C++11)
) noexcept;
template< class T, class U >
std::shared_ptr<T> const_pointer_cast( std::shared_ptr<U>&& r )
(6) (since C++20)
noexcept;
template< class T, class U >
std::shared_ptr<T> reinterpret_pointer_cast( const
(7) (since C++17)
std::shared_ptr<U>& r ) noexcept;
template< class T, class U >
std::shared_ptr<T> reinterpret_pointer_cast( std::shared_ptr<U>&&
(8) (since C++20)
r ) noexcept;

So what's the tea β˜• β€” these functions create a new instance of std::shared_ptr whose stored pointer is obtained from r's stored pointer using a cast expression. That's it, that's the whole vibe.

If r is empty, so is the new shared_ptr β€” but lowkey its stored pointer is not necessarily null, so don't come for me if it's weird πŸ™ˆ. Otherwise, the new shared_ptr will share ownership with the initial value of r, except it's empty if the dynamic_cast performed by dynamic_pointer_cast returns a null pointer. Main character behavior honestly.

Let Y be typename std::shared_ptr<T>::element_type πŸ‘‘ β€” then the resulting std::shared_ptr's stored pointer will be obtained by evaluating, respectively:

  1. 1,2) static_cast<Y*>(r.get())
  2. 3,4) dynamic_cast<Y*>(r.get()). If the result of the dynamic_cast is a null pointer value, the returned shared_ptr will be empty.
  3. 5,6) const_cast<Y*>(r.get())
  4. 7,8) reinterpret_cast<Y*>(r.get())
⚠️ bestie, listen β€” the behavior of these functions is undefined unless the corresponding cast from U* to T* is well formed. Not "undefined" like "haha who knows," undefined like πŸ’€ undefined πŸ’€. So pay attention:
  • 1,2) The behavior is undefined unless static_cast<T*>((U*)nullptr) is well formed.
  • 3,4) The behavior is undefined unless dynamic_cast<T*>((U*)nullptr) is well formed.
  • 5,6) The behavior is undefined unless const_cast<T*>((U*)nullptr) is well formed.
  • 7,8) The behavior is undefined unless reinterpret_cast<T*>((U*)nullptr) is well formed.

After calling the rvalue overloads (2,4,6,8), r is empty and r.get() == nullptr β€” except that r is not modified for dynamic_pointer_cast (4) (since C++20) if the dynamic_cast fails. She's special like that, we stan πŸ’œ


🧚 Parameters 🧚

  • r β€” the pointer to convert πŸ’« (literally just the pointer, bestie, that's the whole parameter, go off)

πŸ“ Notes πŸ“

So you might be looking at std::shared_ptr<T>(static_cast<T*>(r.get())), std::shared_ptr<T>(dynamic_cast<T*>(r.get())), and std::shared_ptr<T>(const_cast<T*>(r.get())) and thinking "hmm, those look like they do the same thing, why do these functions even exist 😭". And like… they might seem to have the same effect, but they all will likely result in undefined behavior β€” attempting to delete the same object twice! 🚨 Not the slay you want. So use the functions, not those expressions, periodt.


πŸŽ€ Possible implementation πŸŽ€

Here's roughly how the girlies are built β€” presenting, in order:

static_pointer_cast

template<class T, class U>
std::shared_ptr<T> static_pointer_cast(const std::shared_ptr<U>& r) noexcept
{
    auto p = static_cast<typename std::shared_ptr<T>::element_type*>(r.get());
    return std::shared_ptr<T>{r, p};
}

dynamic_pointer_cast

template<class T, class U>
std::shared_ptr<T> dynamic_pointer_cast(const std::shared_ptr<U>& r) noexcept
{
    if (auto p = dynamic_cast<typename std::shared_ptr<T>::element_type*>(r.get()))
        return std::shared_ptr<T>{r, p};
    else
        return std::shared_ptr<T>{};
}

const_pointer_cast

template<class T, class U>
std::shared_ptr<T> const_pointer_cast(const std::shared_ptr<U>& r) noexcept
{
    auto p = const_cast<typename std::shared_ptr<T>::element_type*>(r.get());
    return std::shared_ptr<T>{r, p};
}

reinterpret_pointer_cast

template<class T, class U>
std::shared_ptr<T> reinterpret_pointer_cast(const std::shared_ptr<U>& r) noexcept
{
    auto p = reinterpret_cast<typename std::shared_ptr<T>::element_type*>(r.get());
    return std::shared_ptr<T>{r, p};
}

🌈 Example 🌈

// Run this code β€” yes bestie, run it, I believe in you πŸ’–

#include <iostream>
#include <memory>

class Base
{
public:
    int a;
    virtual void f() const { std::cout << "I am base!\n"; }
    virtual ~Base() {}
};

class Derived : public Base
{
public:
    void f() const override { std::cout << "I am derived!\n"; }
    ~Derived() {}
};

int main()
{
    auto basePtr = std::make_shared<Base>();
    std::cout << "Base pointer says: ";
    basePtr->f();

    auto derivedPtr = std::make_shared<Derived>();
    std::cout << "Derived pointer says: ";
    derivedPtr->f();

    // static_pointer_cast to go up class hierarchy
    basePtr = std::static_pointer_cast<Base>(derivedPtr);
    std::cout << "Base pointer to derived says: ";
    basePtr->f();

    // dynamic_pointer_cast to go down/across class hierarchy
    auto downcastedPtr = std::dynamic_pointer_cast<Derived>(basePtr);
    if (downcastedPtr)
    {
        std::cout << "Downcasted pointer says: ";
        downcastedPtr->f();
    }

    // All pointers to derived share ownership
    std::cout << "Pointers to underlying derived: "
              << derivedPtr.use_count()
              << '\n';
}

Output: πŸ‘‘

Base pointer says: I am base!
Derived pointer says: I am derived!
Base pointer to derived says: I am derived!
Downcasted pointer says: I am derived!
Pointers to underlying derived: 3

Look at that 3 β€” shared ownership ate, no crumbs πŸ”₯


⭐ See also ⭐

  • constructor β€” constructs new shared_ptr (public member function) β€” the OG, the blueprint, the mother of them all πŸ‘‘

okay that's the whole page bestie, you're officially a shared_ptr casting expert now, no cap πŸ§šπŸ’œ

this page came to you courtesy of http://cppreference.com, dated 2024.06.10, filed under std::static...ointer_cast,(3) β€” mwah, kisses, go write some well-formed casts πŸŽ€πŸ’…

πŸ“¦ where this page comes from