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) // 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 丟擲異常 (函式) |