std::exception_ptr
從 cppreference.com
在標頭 <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(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); } // std::out_of_range 的析构函数调用于此,此时析构 ept
可能的輸出:
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 拋出異常 (函數) |