std::exception_ptr
来自 cppreference.cn
定义于头文件 <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) // passing by value is OK { 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); // this generates a std::out_of_range } catch(...) { eptr = std::current_exception(); // capture } handle_eptr(eptr); } // destructor for std::out_of_range called here, when the eptr is destructed
可能的输出
Caught exception: 'basic_string::at: __n (which is 1) >= this->size() (which is 0)'
[编辑] 参阅
(C++11) |
从异常对象创建 std::exception_ptr (函数模板) |
(C++11) |
将当前异常捕获到 std::exception_ptr 中 (函数) |
(C++11) |
从 std::exception_ptr 抛出异常 (函数) |