Namespaces
Variants

std:: bad_weak_ptr

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
定义于头文件 <memory>
class bad_weak_ptr ;
(C++11 起)

std::bad_weak_ptr 是当以 std::shared_ptr 的构造函数接收 std::weak_ptr 作为参数,且该 std::weak_ptr 指向已删除对象时,所抛出异常的对象类型。

cpp/error/exception std-bad weak ptr-inheritance.svg

继承关系图

目录

成员函数

(constructor)
构造新的 bad_weak_ptr 对象
(公开成员函数)
operator=
替换 bad_weak_ptr 对象
(公开成员函数)
what
返回说明性字符串
(公开成员函数)

std::bad_weak_ptr:: bad_weak_ptr

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

构造一个新的 bad_weak_ptr 对象,该对象包含一个实现定义的以空字符结尾的字节字符串,可通过 what() 访问。

1) 默认构造函数。
2) 拷贝构造函数。如果 * this other 都具有动态类型 std::bad_weak_ptr ,则满足 std:: strcmp ( what ( ) , other. what ( ) ) == 0

参数

other - 要拷贝的另一个异常对象

std::bad_weak_ptr:: operator=

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

将内容赋值为 other 的内容。如果 * this other 都具有动态类型 std::bad_weak_ptr ,则在赋值后满足 std:: strcmp ( what ( ) , other. what ( ) ) == 0

参数

other - 用于赋值的另一个异常对象

返回值

* this

std::bad_weak_ptr:: what

virtual const char * what ( ) const noexcept ;
(since C++11)

返回解释性字符串。

返回值

指向实现定义的以空字符结尾的字符串的指针,该字符串包含解释性信息。该字符串适合转换并显示为 std::wstring 。该指针保证至少在获取它的异常对象被销毁之前,或者在异常对象上调用非const成员函数(例如拷贝赋值运算符)之前保持有效。

注解

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

继承自 std:: exception

成员函数

[virtual]
销毁异常对象
( std::exception 的虚公开成员函数)
[virtual]
返回说明性字符串
( std::exception 的虚公开成员函数)

示例

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

可能的输出:

std::bad_weak_ptr

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确行为
LWG 2376 C++11 对默认构造的 bad_weak_ptr 调用 what 方法被要求返回 "bad_weak_ptr" 返回值由实现定义

参见

(C++11)
具有共享对象所有权语义的智能指针
(类模板)
(C++11)
对由 std::shared_ptr 管理的对象的弱引用
(类模板)