◐ Shell
clean mode source ↗

std::bad_weak_ptr - cppreference.com

来自cppreference.com

(C++11 起)

std::bad_weak_ptrstd::shared_ptrstd::weak_ptr 为参数的构造函数,在 std::weak_ptr 指代已被删除的对象时,作为异常抛出的对象类型。

cpp/error/exception

继承图

成员函数

构造新的 bad_weak_ptr 对象
(公开成员函数)
替换 bad_weak_ptr 对象
(公开成员函数)
返回解释字符串
(公开成员函数)

std::bad_weak_ptr::bad_weak_ptr

(1) (C++11 起)
bad_weak_ptr( const bad_weak_ptr& other ) noexcept;
(2) (C++11 起)

构造新的拥有实现定义的空终止字节字符串的 bad_weak_ptr 对象,字符串能通过 what() 访问。

1) 默认构造函数。

2) 复制构造函数。如果 *thisother 均拥有动态类型 std::bad_weak_ptr,那么 std::strcmp(what(), other.what()) == 0

参数

std::bad_weak_ptr::operator=

bad_weak_ptr& operator=( const bad_weak_ptr& other ) noexcept;
(C++11 起)

other 的内容赋值。如果 *thisother 均拥有动态类型 std::bad_weak_ptr,那么赋值后 std::strcmp(what(), other.what()) == 0

参数

返回值

*this

std::bad_weak_ptr::what

virtual const char* what() const noexcept;
(C++11 起)
(C++26 起为 constexpr)

返回解释字符串。

返回值

指向有由实现定义的解释信息的空终止字符串的指针。该字符串适合转换并显示为 std::wstring。保证该指针至少直到获得它来源的异常对象被销毁,或在该异常对象上调用非 const 成员函数(例如复制赋值运算符)为止一直有效。

返回的字符串在常量求值过程中按普通字面量编码。

(C++26 起)

注解

允许但不要求实现覆写 what()

注解

功能特性测试 标准 功能特性
__cpp_lib_constexpr_memory 202506L (C++26) constexpr 的 std::bad_weak_ptr

示例

#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';
    }
}

可能的输出:

缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 2376 C++11 要求在默认构造的 bad_weak_ptr 上调用 what 返回 "bad_weak_ptr" 返回值为实现定义

参阅