Does forbidding copy operations automatically forbid move operations? [duplicate]

只愿长相守 提交于 2019-12-10 19:19:05

问题


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?


回答1:


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.




回答2:


Although Brian has probably given you the information you care about, let me try to add just a little bit more (or maybe just get pedantic about wording in a way nobody cares about).

Deleting the copy constructor or copy assignment operator prevents the compiler from implicitly synthesizing a move constructor/move assignment operator.

You can still explicitly define a move constructor and/or move assignment yourself though. So, preventing copies does not actually prevent move construction and move assignment--it just prevents the compiler from implementing them implicitly.



来源:https://stackoverflow.com/questions/39417395/does-forbidding-copy-operations-automatically-forbid-move-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!