c++operatorscopy-constructor

Why and when to delete copy constructor and operator=


Why it is useful to explicitly 'disable' or delete the = operator and copy constructor of a class:

SomeClass& operator=(SomeClass&) = delete;
SomeClass(SomeClass&) = delete;

I guess this makes sense if the class is a singleton. But are there any other situations? (Maybe this has something to do with performance issues?)


Solution

  • This has nothing to do with performance. You disallow copying whenever it does not make sense to copy your class, i.e. if it is not clear what copying the class in question would mean.

    Famous examples are the standard IO streams with their complex internal state and std::unique_ptr which can't be copied because, well, it is the unique pointer pointing to its managed object.