首页 > 解决方案 > 为什么 valueType 的 std::any & operator= 不是有条件的 noexcept?

问题描述

这个问题很简单。

这是模板化 operator= for 的声明std::any

template<typename ValueType>
any& operator=( ValueType&& rhs );

我希望它是:

template<typename ValueType>
any& operator=( ValueType&& rhs ) noexcept(noexcept(std::declval<std::any>() = std::forward<ValueType>(std::declval<ValueType>()));

也就是说,如果您可以以 noexcept 方式将 ValueType 复制分配给 any,那么您应该能够拥有 noexcept。

也许我错过了一些东西。

标签: c++c++17assignment-operatoranynoexcept

解决方案


字面上的答案是这样的规范将是递归的(您是说noexcept如果赋值是 ,则赋值应该是noexcept)。

但是可能更有用的答案是,由于any可能必须分配,因此您只能noexcept在以下情况下decay_t<ValueType>真正分配

  • 足够小(以至于不需要分配),并且
  • nothrow move 可构造,并且
  • nothrow 可从ValueType

指定条件的唯一方法是noexcept要求您还指定“足够小”的含义 - 这将限制实现自由,以获得可疑的收益。

标准库通常不使用有条件的 noexcept - 那么为什么这是......异常?


推荐阅读