c++ - 移动赋值运算符的异常说明符如何影响移动构造函数的异常说明符?

标签 c++ exception language-lawyer c++14 noexcept

我在 C++14 模式下使用 GCC 5.2 和 clang 3.6 进行测试,它们提供相同的输出。

对于下面的代码

#include <iostream>
#include <type_traits>

struct S {
  // S& operator= (S&&) noexcept { return *this; }
};


int main() {
  std::cout << std::is_nothrow_move_constructible<S>::value
            << std::is_nothrow_move_assignable<S>::value;  
}

得到结果11。但如果取消注释移动赋值运算符,输出将变为 01。移动赋值运算符的显式 noexcept 规范如何影响移动构造函数的规范?

最佳答案

通过定义移动赋值运算符,由于 rule of 5,您禁用了移动构造函数.该类不是 is_nothrow_move_constructible 因为它根本不可移动构造,除非您定义该构造函数,否则该构造函数不再可用。

§12.8 复制和移动类对象

If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if
X does not have a user-declared copy constructor,
X does not have a user-declared copy assignment operator,
X does not have a user-declared move assignment operator,
X does not have a user-declared destructor, and
— the move constructor would not be implicitly defined as deleted.

在您没有用户定义的移动构造函数的情况下,两者都被隐式定义并遵循以下规范。

§15.4 异常规范

An implicitly declared special member function shall have an exception-specification. If f is an implicitly declared default constructor, copy constructor, move constructor, destructor, copy assignment operator, or move assignment operator, its implicit exception-specification specifies the type-id T if and only if T is allowed by the exception-specification of a function directly invoked by f’s implicit definition; f shall allow all exceptions if any function it directly invokes allows all exceptions, and f shall allow no exceptions if every function it directly invokes allows no exceptions.

关于c++ - 移动赋值运算符的异常说明符如何影响移动构造函数的异常说明符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33057562/

相关文章:

c++ - Lapackpp 与 Boost BLAS

c++ - 如何在同一程序中使用标准 C++ 代码和 Qt 代码?

c++ - 最小化时 DirectX 崩溃

c++ - 流缓冲区之间的 block 级数据复制

c++ - Lambda 捕获数组元素失败

c++ - 为什么我的程序在析构函数抛出异常时终止?

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

Java:从流读取时如何避免 NullPointerException?

c - 如何用 extern 解决新声明的多个先前声明?

c++ - 在同一 if 语句中检查空指针 && 指针->成员值