Namespaces
Variants

std:: exception_ptr

From cppreference.net
定义于头文件 <exception>
using exception_ptr = /*未指明*/
(C++11 起)

std::exception_ptr 是一种可空指针式类型,用于管理已被抛出并通过 std::current_exception 捕获的异常对象。 std::exception_ptr 的实例可以传递给其他函数(可能在不同线程中),在该处异常可被重新抛出并通过 catch 子句处理。

默认构造的 std::exception_ptr 是一个空指针;它不指向任何异常对象。

两个 std::exception_ptr 实例仅在两者均为空或指向同一异常对象时才比较相等。

std::exception_ptr 不能隐式转换为任何算术类型、枚举类型或指针类型。它可上下文转换为 bool 类型,若其为空则求值结果为 false ,否则为 true

std::exception_ptr 引用的异常对象会保持有效,只要至少存在一个 std::exception_ptr 正在引用它: std::exception_ptr 是一个共享所有权的智能指针(注意:这是对常规 异常对象生命周期规则 的额外补充)。

std::exception_ptr 满足 NullablePointer 的要求。

示例

#include <exception>
#include <iostream>
#include <stdexcept>
#include <string>
void handle_eptr(std::exception_ptr eptr) // 按值传递是可接受的
{
    try
    {
        if (eptr)
            std::rethrow_exception(eptr);
    }
    catch(const std::exception& e)
    {
        std::cout << "Caught exception: '" << e.what() << "'\n";
    }
}
int main()
{
    std::exception_ptr eptr;
    try
    {
        [[maybe_unused]]
        char ch = std::string().at(1); // 此处会生成 std::out_of_range 异常
    }
    catch(...)
    {
        eptr = std::current_exception(); // 捕获异常
    }
    handle_eptr(eptr);
} // 当 eptr 被销毁时,std::out_of_range 的析构函数在此处调用

可能的输出:

Caught exception: 'basic_string::at: __n (which is 1) >= this->size() (which is 0)'

参阅

从异常对象创建 std::exception_ptr
(函数模板)
std::exception_ptr 中捕获当前异常
(函数)
std::exception_ptr 抛出异常
(函数)