问题
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, andX
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