加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么`std:variant`的`operator =(T \u0026\u0

发布时间:2020-12-16 09:21:58 所属栏目:百科 来源:网络整理
导读:长标题:为什么std:variant的operator =(T t)的noexcept规范不依赖于内部类型的析构函数的noexcept规范? 我可以在cppreference上看到 template class T variant operator=(T t) noexcept(/* see below */); 是 noexcept(std::is_nothrow_assignable_vT_j,T
长标题:为什么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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读