gpt4 book ai didi

c++ - 为什么 std::unique_ptr::reset() 总是无异常?

转载 作者:IT老高 更新时间:2023-10-28 12:39:30 27 4
gpt4 key购买 nike

A recent question (尤其是我的回答)让我想知道:

在 C++11(和更新的标准)中,析构函数总是隐式的 noexcept , 除非另有说明(即 noexcept(false) )。在这种情况下,这些析构函数可以合法地抛出异常。 (请注意,这仍然是一种你应该真正知道自己在做什么——那种情况!)

然而,所有的重载 std::unique_ptr<T>::reset()被声明为始终为 noexcept (见 cppreference ),即使析构函数 if T不是,如果析构函数在 reset() 期间抛出异常,将导致程序终止.类似情况适用于 std::shared_ptr<T>::reset() .

为什么是reset()总是 noexcept,而不是有条件地 noexcept?

应该可以声明noexcept(noexcept(std::declval<T>().~T()))如果 T 的析构函数,这使得它完全没有异常(exception)。是没有异常(exception)。我是否在这里遗漏了什么,或者这是对标准的疏忽(因为这无疑是一个高度学术化的情况)?

最佳答案

函数对象的调用要求 Deleter std::unique_ptr<T>::reset() 的要求中列出的具体内容成员(member)。

来自 [unique.ptr.single.modifiers]/3 ,大约 N4660 §23.11.1.2.5/3;

unique_ptr modifiers

void reset(pointer p = pointer()) noexcept;

Requires: The expression get_deleter()(get()) shall be well formed, shall have well-defined behavior, and shall not throw exceptions.

一般来说,类型需要是可破坏的。根据 cppreference关于 C++ 概念 Destructible,标准在 [utility.arg.requirements]/2 中的表格下列出了这一点。 , §20.5.3.1(强调我的);

Destructible requirements

u.~T() All resources owned by u are reclaimed, no exception is propagated.

还要注意替换函数的一般库要求; [res.on.functions]/2 .

关于c++ - 为什么 std::unique_ptr::reset() 总是无异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48861586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com