Deleting copy constructors and copy assignment operators. Which of them are essential?

hkBattousai picture hkBattousai · Nov 18, 2015 · Viewed 9.6k times · Source

I have a use case that my object must not be copied in any way. I have written an exaggerated complete list of copy constructor and copy assignment operator deletions below. There are so many of them that I can't make sure which ones to use, and sometimes this makes me paranoid. I don't have to write them all in my code, do I? So, in order to prevent object copying of any kind, which of them should I use?

        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;

Answer

TartanLlama picture TartanLlama · Nov 18, 2015

You only need to mark a single copy constructor and copy assignment operator as delete. The presence of the copy versions will prevent the implicit-declaration of the move constructor and move assignment operator, and declaring one form of a copy special member function suppresses the implicit-declaration of other forms.

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

Note that post-C++11, implicit-definition of the assignment operator as defaulted is deprecated and it should instead be defined as deleted.