std::exception_ptr

定义于头文件 <exception>
typedef /*unspecified*/ 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 <iostream>
#include <string>
#include <exception>
#include <stdexcept>
 
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 {
        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"

参阅

从异常对象创建一个std::exception_ptr
(函数模板)
std::exception_ptr 中捕获当前异常
(函数)
从一个 std::exception_ptr 抛出异常
(函数)

版本历史

  • (当前 | 先前 2017年5月17日 (三) 09:20Fruderica讨论 | 贡献. . (1,452字节) (-999). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 17:45P12bot讨论 | 贡献 . . (2,451字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 09:03P12bot讨论 | 贡献 . . (2,451字节) (-53). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 15:54P12bot讨论 | 贡献 . . (2,504字节) (+249). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 11:36P12讨论 | 贡献 . . (2,255字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 07:00TranslationBot讨论 | 贡献. . (2,255字节) (-29). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月25日 (四) 14:25P12讨论 | 贡献 . . (2,284字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 13:00TranslationBot讨论 | 贡献. . (2,284字节) (+2,284). . (Translated from the English version using Google Translate)