c++ - std::exception_ptr 存储的生命周期要求

标签 c++ c++11 exception

给出 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

最佳答案

是的,该程序有效。

来自 cppreference:

The exception object referenced by an std::exception_ptr remains valid as long as there remains at least one std::exception_ptr that is referencing it: std::exception_ptr is a shared-ownership smart pointer

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

关于c++ - std::exception_ptr 存储的生命周期要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38523864/

相关文章:

.net - 无法在 StorageException 处理程序中续订 Windows Azure SAS key

c++ - 如何为模板类编写复制构造函数 - C++

c++ 12位变量,我该怎么做?

c++ - 对象数组融合的通用函数

c++ - 有没有办法缩短声明中的 C++11 lambda 签名?

c# - .Net WebException 检查本地机器是否可以访问互联网

c++ - 没有 typedef 的可变参数扩展器

c++ - 使用 lambda 作为参数:std::function 还是模板?

c++ - std::unique_ptr<T[]>::reset 在 gcc 6 中的实现

c# - 无法将 COM 对象转换为类类型