【问题标题】:Lifetime requirements for storage of std::exception_ptr存储 std::exception_ptr 的生命周期要求
【发布时间】:2016-07-22 10:14:50
【问题描述】:

鉴于cppreference.com 中关于std::exception_ptr 的示例,以下列方式缩短代码是否合法? 如果所有处理都在 catch-block 内完成,则无需将 std::exception_ptr 存储在外部甚至全局范围内。

#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
 
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()
{
    try {
        std::string().at(1); // this generates an std::out_of_range
    } catch(...) {
        handle_eptr(std::current_exception()); // CHANGE: HANDLING THE std::exception_ptr AS R-VALUE INSIDE THE CATCH BLOCK
    }
} // destructor for std::out_of_range called here, when the eptr is destructed

【问题讨论】:

    标签: c++ c++11 exception


    【解决方案1】:

    是的,程序是有效的。

    来自 cppreference:

    std::exception_ptr 引用的异常对象仍然有效 只要还有至少一个 std::exception_ptr 是 引用它:std::exception_ptr 是共享所有权智能指针

    在这种情况下,eptr 将确保从std::current_exception 返回的值不会超出范围。如有疑问,请认为std::exception_ptr 的生命周期遵循与std::shared_ptr 相同的范围规则,因为它们都是“共享所有权智能指针”

    【讨论】:

      【解决方案2】:

      当然,但是 cppreference 代码的重点是异常指针允许您在 catch 块之外保持异常的生命周期,并且无需重新抛出。

      所以你的代码看起来合法,但它不能满足 cppreference 代码的目的。

      【讨论】:

      • 也许我的目的略有不同。我已经很高兴能够外包(更少的代码重复)一个成熟的异常处理程序来处理各种异常,包括日志记录工具。因此我不需要延长寿命。
      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 2015-03-29
      • 2021-11-20
      • 2017-06-18
      • 1970-01-01
      • 2017-09-28
      • 2020-04-27
      • 2021-12-17
      相关资源
      最近更新 更多