Namespaces
Variants
Views
Actions

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

From cppreference.com
< cpp‎ | memory‎ | shared ptr
 
 
 
 
 
template< class T, class U >
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r );
(1) (since C++11)
template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r );
(2) (since C++11)
template< class T, class U >
std::shared_ptr<T> const_pointer_cast( const std::shared_ptr<U>& r );
(3) (since C++11)

Creates a new instance of std::shared_ptr whose managed object type is obtained from the r's managed object type using a cast expression. Both smart pointers will share the ownership of the managed object.

The resulting std::shared_ptr's managed object will be obtained by calling (in respective order):

1) static_cast<T*>(r.get()).
2) dynamic_cast<T*>(r.get()) (If the result of the dynamic_cast is a null pointer value, the returned shared_ptr will be empty).
3) const_cast<T*>(r.get()).

In any case, if the parameter r is an empty std::shared_ptr the result will be a new empty std::shared_ptr.

Contents

[edit] Parameters

r - The pointer to convert

[edit] Exceptions

noexcept specification:  
noexcept
  

[edit] Notes

The expressions 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())) seem to have the same effect, but they all will eventually result in undefined behavior, attempting to delete the same object twice.

[edit] Possible implementation

First version
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);
}
Second version
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>();
    }
}
Third version
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);
}

[edit] Example

[edit] See also

constructs new shared_ptr
(public member function) [edit]