禁止复制操作是否自动禁止移动操作? [英] Does forbidding copy operations automatically forbid move operations?

查看:150
本文介绍了禁止复制操作是否自动禁止移动操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

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

//禁用复制
MyClass(const MyClass&)= delete;
MyClass& operator =(const MyClass&)= delete;
};作为一个测试,我尝试调用 std :: move()

code>在类实例上,似乎没有移动操作自动生成,因为Visual Studio 2015 C ++编译器产生错误消息。



这是一个特定于MSVC 2015的行为,或者是由C ++标准规定,通过 = delete 复制操作自动禁用禁用移动构造函数和移动赋值? / p>

解决方案

MSVC符合这种情况下的标准。在C ++ 14中的[class.copy] / 9中读取:


如果类的定义 / code>没有显式地声明一个移动构造函数,当且仅当




    时,将默认声明
    > X 没有用户声明的复制构造函数
  • X 没有用户声明的复制赋值运算符,

  • X 没有用户声明的移动赋值运算符, li>
  • X 没有用户声明的析构函数。


< blockquote>

所以你的类有没有移动构造函数,任何移动它的尝试都会回到删除的拷贝构造函数。


I want to write a C++ class without any copy and move semantics: I'm just interested in its constructor and destructor.

I disabled copy operations (i.e. copy constructor and copy assignment operator) explicitly using C++11's =delete syntax, e.g.:

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

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

As a test, I tried calling std::move() on class instances, and it seems that there are no move operations automatically generated, as the Visual Studio 2015 C++ compiler emits error messages.

Is this a behavior specific to MSVC 2015, or is it dictated by the C++ standard that disabling via =delete copy operations automatically disables move constructor and move assignment?

解决方案

MSVC conforms to the standard in this case. [class.copy]/9 in C++14 reads:

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.

So your class has no move constructor and any attempt to move it will fall back to the deleted copy constructor.

这篇关于禁止复制操作是否自动禁止移动操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆