c++ - unique_ptr<T,Deleter> 构造函数要求 Deleter 不抛出异常

标签 c++ c++17 language-lawyer noexcept

unique_ptr (constructor) @ cppreference

unique_ptr( pointer p, /* see below */ d1 ) noexcept;
(3) 
unique_ptr( pointer p, /* see below */ d2 ) noexcept;
(4)

这里有 2 个构造函数,Deleter 案例的描述非引用

a) If D is non-reference type A, then the signatures are:
unique_ptr(pointer p, const A& d) noexcept;
(1) (requires that Deleter is nothrow-CopyConstructible)
unique_ptr(pointer p, A&& d) noexcept;
(2) (requires that Deleter is nothrow-MoveConstructible)

我检查了 gcc 和 llvm 代码,但没有看到强制执行 nothrot 要求。构造函数 3-4 被标记为 noexcept,因此在调用构造函数时,Deleter 不应抛出异常。但我不确定为什么在他们提供的示例中,构造函数没有标记为 noexcept

struct D { // deleter
    D() {};
    D(const D&) { std::cout << "D copy ctor\n"; }
    D(D&) { std::cout << "D non-const copy ctor\n";}
    D(D&&) { std::cout << "D move ctor \n"; }
    void operator()(Foo* p) const {
        std::cout << "D is deleting a Foo\n";
        delete p;
    };
};

最佳答案

I checked both gcc and llvm code but I don't see nothrow requirement is enforced.

它不是直接强制执行的。
这是actual words from the standard :

For the first constructor, if D is not a reference type, D shall meet the Cpp17CopyConstructible requirements and such construction shall not exit via an exception. For the second constructor, if D is not a reference type, D shall meet the Cpp17MoveConstructible requirements and such construction shall not exit via an exception.

这意味着,如果您的复制/移动构造函数通过异常退出,则会出现未定义的行为。 [在这种情况下,“应”是对用户的要求。 ]

如果幸运的话,程序将调用terminate并带有一条友好的消息。但是,您没有任何保证。

(稍后)注意:要求不是它们是 noexcept,而是它们不通过异常退出。这就是为什么 cppreference 上的示例很好。

关于c++ - unique_ptr<T,Deleter> 构造函数要求 Deleter 不抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61603288/

相关文章:

c++ - 未定义模板 “std::__1::basic_istringstream<char, std::__1::char_traits<char>, std::__1::allocator<char>>”的隐式实例化

C++:使用整数 move 语义

c++ - 为什么我的热插拔 HID 设备应用程序在每次连接时变得越来越慢?

c++ - 模板模板参数的替换失败

c++ - 如何将 C++ range-v3 输出到 ostringstream?

c++ - 在非 `constexpr` 上下文 : clang vs gcc 中的 -`constexpr` 函数中使用 lambda

c++ - 在 C++ 中从文本文件中读取数值的最快方法(在这种情况下为 double )

c++ - 评估对象的创建是什么意思?

c++ - 在预处理器条件中使用 bool 文字是否有效?

c++ - 在 constexpr 函数中实例化多个模板