禁止复制操作是否自动禁止移动操作?

Does forbidding copy operations automatically forbid move operations?

我想写一个没有任何复制和移动语义的 C++ class:我只对它的构造函数和析构函数感兴趣。

我禁用了复制操作(即复制构造函数和复制赋值运算符)显式 使用 C++11 的 =delete 语法,例如:

class MyClass 
{
  public:    
    MyClass()  { /* Init something */    }
    ~MyClass() { /* Cleanup something */ }

    // Disable copy
    MyClass(const MyClass&) = delete;
    MyClass& operator=(const MyClass&) = delete;
};

作为测试,我尝试在 class 实例上调用 std::move(),似乎没有自动生成移动操作,因为 Visual Studio 2015 C++ 编译器发出错误消息.

这是 MSVC 2015 特有的行为,还是 C++ 标准规定通过 =delete 复制操作禁用 自动 禁用移动构造函数和移动赋值?

本例MSVC符合标准。 [class.copy]/9 在 C++14 中读取:

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, and
  • X does not have a user-declared destructor.

因此您的 class 没有 移动构造函数,任何移动它的尝试都将回退到已删除的复制构造函数。

尽管 Brian 可能 已经向您提供了您关心的信息,但让我尝试添加更多(或者可能只是以一种没人关心的方式对措辞迂腐约)。

删除复制构造函数或复制赋值运算符可防止编译器隐式合成移动 constructor/move 赋值运算符。

您仍然可以自己显式定义移动构造函数 and/or 移动赋值。因此,阻止复制实际上并不能阻止移动构造和移动赋值——它只是阻止编译器隐式实现它们。