使课程不可复制*并且*不可移动 [英] Make a class non-copyable *and* non-movable
问题描述
在C ++ 11之前,我可以使用它来使类不可复制:
Before C++11, I could use this to make a class non-copyable:
private:
MyClass(const MyClass&);
MyClass& operator=(const MyClass&);
使用C ++ 11,我可以改为:
With C++11, I can do it like this instead:
MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;
在将类与已删除的副本和分配一起使用时,是否有可能生成默认的move运算符?并且该类不是被完全复制,而是毕竟被移动了(有点相似)?
When using the class with the deleted copy and assignment, is there a chance that a default move operator is generated? And the class is not exactly copied, but moved (which is sort of similar) after all?
因此,我是否必须这样做以防止默认移动构造和分配:
So, do I have to do this to prevent default move construction and assignmnent:
MyClass(MyClass&&) = delete;
MyClass& operator=(MyClass&&) = delete;
...?
推荐答案
正如注释中已经提到的其他内容一样,C ++ 11中引入了删除的构造函数.要回答您的问题,通常遵循以下规则:
As others already mentioned in the comments, deleted constructors was introduced in C++11. To answer your question, the following rules hold in general:
- 这两个复制操作是独立的.声明副本构造函数不会阻止编译器生成副本分配,反之亦然. (与C ++ 98中的相同)
- 移动操作不是独立的.声明其中一个会阻止编译器生成另一个. (不同于复制操作.)
- 如果声明了任何复制操作,则不会生成任何移动操作. (根据您的情况)
- 如果声明了任何移动操作,则不会生成任何复制操作.这与以前的规则相反.
- 如果声明了析构函数,则不会生成任何移动操作.仍会生成复制操作,以实现与C ++ 98的反向兼容性.
- 仅当未声明构造函数时才生成默认构造函数. (与C ++ 98中的相同)
- The two copy operations are independent. Declaring copy constructor does not prevent compiler to generate copy assignment and vice versa. (Same as in C++98)
- Move operations are not independent. Declaring either one of them prevents the compiler to generate the other. (Different from copy operations.)
- If any of the copy operations is declared, then none of the move operation will be generated. (Your case.)
- If any of the move operation is declared, then none of the copy operation will be generated. This is the opposite rule of the previous.
- If a destructor is declared, then none of the move operation will be generated. Copy operations are still generated for reverse compatibility with C++98.
- Default constructor generated only when no constructor is declared. (Same as in C++98)
As requested in the comments, here are some sources (C++11 is draft N3242):
- 复制操作:§12.8.8,§12.8.19
- 移动操作:第12.8.10节,第12.8.21节
- 默认构造函数:第12.1.5节
这篇关于使课程不可复制*并且*不可移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!