名前空間
変種
操作

std::exception_ptr

From cppreference.com
< cpp‎ | error
 
 
 
ヘッダー <exception> で定義
using exception_ptr = /*unspecified*/
(C++11以降)

std::exception_ptr は、std::current_exception でスローされ捕捉された例外オブジェクトを管理する、null 許容なポインタのような型です。std::exception_ptr のインスタンスは、おそらく別のスレッドで、別の関数に渡され、そこで例外が再スローされ、catch 句で処理されることがあります。

デフォルト構築された std::exception_ptr はヌルポインタです。例外オブジェクトを指しません。

2つの std::exception_ptr インスタンスが等しいと評価されるのは、両方ともヌルであるか、両方とも同じ例外オブジェクトを指している場合のみです。

std::exception_ptr は、算術型、列挙型、またはポインタ型に暗黙的に変換されません。文脈的に bool に変換可能であり、ヌルであれば false、そうでなければ true と評価されます。

std::exception_ptr によって参照される例外オブジェクトは、それを参照する std::exception_ptr が少なくとも1つ存在する限り有効です。std::exception_ptr は共有所有権スマートポインタです(注: これは通常の例外オブジェクトの寿命ルールに加えてです)。

std::exception_ptrNullablePointerの要件を満たします。

[編集]

#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)'

[編集] 関連項目

例外オブジェクトから std::exception_ptr を作成する
(関数テンプレート) [編集]
現在の例外を std::exception_ptr に捕捉する
(関数) [編集]
std::exception_ptr から例外をスローする
(関数) [編集]
English 日本語 中文(简体) 中文(繁體)