简体   繁体   中英

Why and when delete copy constructor and operator=

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?)

This has nothing to do with performance. You disallow copying whenever it does not make sense to copy your class, ie 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.

I think the following is a good addition::

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM