std::exception_ptr

来自cppreference.com
< cpp‎ | error
在标头 <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)// 按值传递 OK{try{if(eptr)std::rethrow_exception(eptr);}catch(conststd::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);   }// std::out_of_range 的析构函数调用于此,此时析构 ept

可能的输出:

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

[编辑]参阅

从异常对象创建一个std::exception_ptr
(函数模板)[编辑]
捕获当前异常到 std::exception_ptr 之中
(函数)[编辑]
从一个 std::exception_ptr 抛出异常
(函数)[编辑]
close