std::rethrow_exception
来自cppreference.com
在标头 <exception> 定义 | ||
[[noreturn]]void rethrow_exception(std::exception_ptr p ); | (C++11 起) (C++26 起为 constexpr) | |
抛出异常指针 p 所引用的先前捕获的异常对象,或其副本。
是否创建副本是未指定的。若创建副本,则以未指定的方式分配其存储。
若 p 为空则行为未定义。
目录 |
[编辑]参数
p | - | 非空 std::exception_ptr |
[编辑]异常
若不创建副本,则为 p 所引用的异常对象。
否则,若实现成功复制异常对象,则为这种异常对象的副本。
否则,若分配或复制失败,则分别为 std::bad_alloc 或复制异常对象时抛出的异常。
[编辑]注解
在 P1675R2 前,rethrow_exception
未被允许复制异常对象,这在一些异常对象分配在栈上的平台上无法实现。
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__cpp_lib_constexpr_exceptions | 202411L | (C++26) | constexpr 的异常类型 |
[编辑]示例
运行此代码
#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)'
[编辑]参阅
(C++11) | 处理异常对象的共享指针类型 (typedef) |
(C++11) | 捕获当前异常到 std::exception_ptr 之中 (函数) |