[英]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:作为 C++ 新手,我想知道为什么显式“禁用”或删除类的 = 运算符和复制构造函数很有用:
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.著名的例子是具有复杂内部状态的标准 IO 流和无法复制的
std::unique_ptr
,因为它是指向其托管对象的唯一指针。
I think the following is a good addition::我认为以下是一个很好的补充:
If you want to disallow passing the object by value, you may delete them.如果您想禁止按值传递对象,您可以删除它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.