删除复制构造函数和复制赋值运算符。哪一项至关重要?

时间:2015-11-18 09:51:44

标签: c++ copy-constructor copy-assignment deleted-functions implicit-methods

我有一个用例,我的对象不能以任何方式复制。我在下面写了一个夸张的复制构造函数和复制赋值运算符删除的完整列表。有这么多,我无法确定使用哪些,有时这让我变得偏执。我不必在我的代码中全部写出来,是吗?那么,为了防止任何类型的对象复制,我应该使用哪些?

        MyClass             (       MyClass &)  = delete;
        MyClass             (const  MyClass &)  = delete;
        MyClass             (       MyClass &&) = delete;
        MyClass             (const  MyClass &&) = delete;
        MyClass    operator=(       MyClass &)  = delete;
        MyClass    operator=(const  MyClass &)  = delete;
const   MyClass    operator=(       MyClass &)  = delete;
const   MyClass    operator=(const  MyClass &)  = delete;
        MyClass &  operator=(       MyClass &)  = delete;
        MyClass &  operator=(const  MyClass &)  = delete;
const   MyClass &  operator=(       MyClass &)  = delete;
const   MyClass &  operator=(const  MyClass &)  = delete;
        MyClass && operator=(       MyClass &)  = delete;
        MyClass && operator=(const  MyClass &)  = delete;
const   MyClass && operator=(       MyClass &)  = delete;
const   MyClass && operator=(const  MyClass &)  = delete;
        MyClass    operator=(       MyClass &&) = delete;
        MyClass    operator=(const  MyClass &&) = delete;
const   MyClass    operator=(       MyClass &&) = delete;
const   MyClass    operator=(const  MyClass &&) = delete;
        MyClass &  operator=(       MyClass &&) = delete;
        MyClass &  operator=(const  MyClass &&) = delete;
const   MyClass &  operator=(       MyClass &&) = delete;
const   MyClass &  operator=(const  MyClass &&) = delete;
        MyClass && operator=(       MyClass &&) = delete;
        MyClass && operator=(const  MyClass &&) = delete;
const   MyClass && operator=(       MyClass &&) = delete;
const   MyClass && operator=(const  MyClass &&) = delete;

2 个答案:

答案 0 :(得分:23)

您只需要将单个复制构造函数和复制赋值运算符标记为delete。复制版本的存在将阻止移动构造函数和移动赋值运算符的隐式声明,并且声明一种形式的复制特殊成员函数会抑制其他形式的隐式声明。

MyClass (const MyClass&) = delete;
MyClass& operator= (const MyClass&) = delete;

请注意,在C ++ 11之后,不推荐将赋值运算符隐式定义为默认值,而应将其定义为已删除。

答案 1 :(得分:5)

copy constructor

MyClass             (const  MyClass &)  = delete;

assignement operator

MyClass &  operator=(const  MyClass &)  = delete;

这些是隐式定义的唯一复制构造函数和复制赋值运算符。