Why and when delete copy constructor and operator=

2020-03-28 01:03发布

问题:

As a c++ newbe I wondered why it is usefull to explicitely 'disable' or delete the = operator and copy constructor of a class:

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

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

回答1:

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.



回答2:

I think the following is a good addition::

If you want to disallow passing the object by value, you may delete them.