PAYATHON 2026

std::current_exception() 的动机及返回 std::exception_ptr 的原因

数据小陈

结论:std::current_exception() 用来把“当前正在处理的异常”捕获成一个可保存、可复制、可延迟重抛的句柄,它不替代 catch 参数。std::exception_ptr 要独立管理异常对象的生命周期,允许多个副本共享同一个异常对象,又不要求异常类型参与引用计数,普通指针或引用无法提供这些语义。

为什么需要 std::current_exception()

catch (const std::exception& e) 里的 e 只在当前处理块及其同步调用期间有效。把 e 传给同步函数当然没问题;如果这个函数需要把异常存起来、放进队列、交给回调、跨线程传递,或者过一会儿再抛,保存引用或指针就会悬空。catch (...) 甚至没有可用的异常参数。

std::current_exception() 在异常处理期间取得当前异常,返回一个 std::exception_ptr。调用方不需要知道异常类型,也不需要函数签名里出现异常参数,之后就能用 std::rethrow_exception 按原动态类型重新抛出。典型场景包括异步任务、线程间传递错误、future/promise 风格接口、事件循环和延迟错误处理。

为什么返回 std::exception_ptr 而不是普通指针或引用

普通指针或引用不拥有异常对象。catch 块结束后异常对象通常会被销毁,指向它的指针或引用随之悬空。复制异常对象也不总是合适:动态类型可能未知,复制可能切片,标准库也没有要求所有异常都以方便复制的方式暴露给调用方。

std::exception_ptr 是一种类型擦除的可复制句柄。标准没有规定它必须实现为 std::shared_ptr,但语义上需要共享所有权:多个 exception_ptr 副本可以指向同一个异常对象,最后一个副本销毁前异常对象保持有效;任意副本都可以重新抛出该异常。这种共享由 exception_ptr 自身管理,不需要异常类型配合,因此适合“非协作式”的保存和传递。

示例

#include <exception>
#include <iostream>
#include <stdexcept>

std::exception_ptr g_ep;

void save_current_exception() {
    // 应在异常处理期间调用,例如 catch 块内或由其调用的代码中
    g_ep = std::current_exception();
}

void may_throw() {
    throw std::runtime_error("boom");
}

int main() {
    try {
        may_throw();
    } catch (const std::exception& e) {
        std::cout << "caught: " << e.what() << '\n';
        save_current_exception();
    }

    if (g_ep) {
        try {
            std::rethrow_exception(g_ep);
        } catch (const std::exception& e) {
            std::cout << "rethrown: " << e.what() << '\n';
        }
    }
}

注意事项

  • 没有异常正在处理时调用 std::current_exception() 会得到空 exception_ptr,使用前先判断。
  • exception_ptr 不能直接读取异常内容。通常要先用 rethrow_exception 重新抛出,再通过 catch 访问 what() 等接口。
  • 不要把 catch 参数的地址或引用保存到处理块之外;需要延迟处理时改用 std::current_exception()。
  • 标准不保证 exception_ptr 的具体实现是 shared_ptr,不要假设它一定等同于 std::shared_ptr。

备注:内容仅供参考。