Why and when delete copy constructor and operator=

拥有回忆 提交于 2019-12-30 11:09:25

问题


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.



来源:https://stackoverflow.com/questions/34291938/why-and-when-delete-copy-constructor-and-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!