You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boost 1.56.0中如何将捕获的异常赋值给shared_ptr共享指针

Boost 1.56.0 异常对象存入shared_ptr解决方案

你捕获的boost::exception是栈对象的引用,直接取地址赋值给shared_ptr会在catch块结束后触发悬空指针问题,必须先将异常拷贝到堆内存再交给智能指针管理。

可选实现方案

方案1:使用Boost原生异常指针(推荐)

boost::exception_ptr是Boost专门用于异常生命周期管理的类型,会完整保留异常的原始派生类型信息,不会出现类型切割问题,适合需要跨作用域传递、后续重新抛出的场景:

#include <boost/exception_ptr.hpp>

try {
    boost::rethrow(excep);
} catch(boost::exception &e) {
    // 直接获取当前异常的智能指针
    boost::exception_ptr e_ptr = boost::current_exception();

    // 后续需要重新抛出时调用即可
    // boost::rethrow_exception(e_ptr);
}

方案2:生成原生std::shared_ptr

如果必须要std::shared_ptr<boost::exception>类型的指针,可以通过拷贝构造生成堆上的异常对象,注意:该方法会切割异常的派生类内容,仅保留boost::exception基类的成员:

#include <memory>
#include <boost/exception.hpp>

try {
    boost::rethrow(excep);
} catch(boost::exception &e) {
    std::shared_ptr<boost::exception> e_ptr = std::make_shared<boost::exception>(e);
}

注意事项

  • Boost 1.56.0已完整支持上述两种实现,无需额外适配
  • 除非常确定只需要用到boost::exception基类的成员,否则优先选择boost::exception_ptr方案

内容的提问来源于stack exchange,提问作者rajesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 22:36:01