当前位置 : 主页 > 编程语言 > c++ >

c – 为什么`std:variant`的`operator =(T \u0026\u0026 t)`的noexcept规范不依赖于内部类型

来源:互联网 收集:自由互联 发布时间:2021-06-23
长标题:为什么std:variant的operator =(T t)的noexcept规范不依赖于内部类型的析构函数的noexcept规范? 我可以在cppreference上看到 template class T variant operator=(T t) noexcept(/* see below */); 是 noexce
长标题:为什么std:variant的operator =(T& t)的noexcept规范不依赖于内部类型的析构函数的noexcept规范?

我可以在cppreference上看到

template <class T> variant& operator=(T&& t) noexcept(/* see below */);

noexcept(std::is_nothrow_assignable_v<T_j&, T> && 
std::is_nothrow_constructible_v<T_j, T>)

所以这个编译:

struct FooThrow {
  ~FooThrow() noexcept(false) {throw;} 
};
static_assert(std::is_nothrow_assignable_v<std::variant<FooThrow, int>, int>);

但是它调用了FooThrow的析构函数,它是noexcept(false):

std::variant<FooThrow, int> x;
x = 3; // throws

这似乎不对.我错过了什么吗?

通常,标准库类型不适用于具有抛出析构函数的类型.或者特别是,当析构函数实际发出异常时.关于它的一般规则( [res.on.functions])

In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C ++ standard library depends on components supplied by a C ++ program. If these components do not meet their requirements, this International Standard places no requirements on the implementation.

In particular, the effects are undefined in the following cases:

  • if any replacement function or handler function or destructor operation exits via an exception, unless specifically allowed in the applicable Required behavior: paragraph.

由于variant :: operator =没有关于抛出析构函数的特殊声明,因此实际抛出这些析构函数是UB.

网友评论