c++ - std::exception_ptr 复制构造函数可以抛出吗?

标签 c++ c++17

在我看来,标准允许 std::exception_ptr 不使用引用计数(即 std::exception_ptr cctor 可以复制异常对象指着)。这意味着 following code可能永远不会调用 handle_eptr() 并且异常可以逃逸 main() 并产生相关后果:

#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
 
void handle_eptr(std::exception_ptr eptr) // passing by value is ok  <---- ARE YOU SURE?
{
    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); // this generates an std::out_of_range
    } catch(...) {
        eptr = std::current_exception(); // capture
    }
    handle_eptr(eptr);
} // destructor for std::out_of_range called here, when the eptr is destructed

我说的对吗?

最佳答案

Can std::exception_ptr copy constructor throw?

没有。

标准说(最新草案):

[propagation]

exception_­ptr meets the requirements of Cpp17NullablePointer

[nullablepointer.requirements]

No operation which is part of the Cpp17NullablePointer requirements shall exit via an exception.

关于c++ - std::exception_ptr 复制构造函数可以抛出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63476703/

相关文章:

c++ - 如何控制何时使用 initializer_list。局部变量、返回和传递参数

c++ - 如何使用 std::transform 算法将 hash_map<string, string> 转换为 hash_map<wstring, wstring>?

c++ - 运算符重载 : memory leaks

c++ - 缓存未命中对矩阵乘法时间的影响

c++ - 嵌套的 boost (预处理器)序列

c++ - 由于存在默认成员初始化程序,因此类类型很简单

c++ - 为什么在这种情况下非类型模板参数不能是自动的?

c++ - C++17中数组索引范围的并行for循环

c++ - 错误:<位/stdc++。h>,未找到 'cstdalign'文件,正在运行C++ 17

c++ - 函数的多重定义,为什么守卫没有捕获这个?