std::bad_weak_ptr

Header: <memory>

std::bad_weak_ptr is the type of the object thrown as exceptions by the constructors of std::shared_ptr that take std::weak_ptr as the argument, when the std::weak_ptr refers to an already deleted object.

# Declarations

class bad_weak_ptr;

(since C++11)

# Parameters

# Return value

*this

# Notes

Implementations are allowed but not required to override what().

# Example

#include <iostream>
#include <memory>
 
int main()
{
    std::shared_ptr<int> p1(new int(42));
    std::weak_ptr<int> wp(p1);
    p1.reset();
    try
    {
        std::shared_ptr<int> p2(wp);
    }
    catch (const std::bad_weak_ptr& e)
    {
        std::cout << e.what() << '\n';
    }
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2376C++11calling what on a default-constructed bad_weak_ptr was required to return “bad_weak_ptr”the return value is implementation-defined

# See also