简体   繁体   English

为什么以及何时删除复制构造函数和运算符 =

[英]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.

相关问题 为什么删除模板复制构造函数会导致赋值运算符失灵? - Why delete of templete copy constructor cause assignment operator disfunctional? 何时删除复制构造函数 - When to delete copy constructor 为什么在 C++11 或 C++14 中,当我声明移动赋值运算符时,编译器会隐式删除复制构造函数? - Why in C++11 or C++14 does the compiler implicitly delete the copy constructor when I declare a move assignment operator? 为什么会这样? operator =和复制构造函数 - why is this happening ? operator= and copy constructor 为什么声明复制构造函数不会删除复制赋值运算符,反之亦然? - Why does declaring a copy constructor not delete the copy assignment operator and vice versa? 为什么不允许复制构造函数和赋值运算符? - Why copy constructor and assignment operator are disallowed? 为什么不只有一个?复制构造函数和赋值运算符 - Why not only one? Copy constructor and assignment operator 当有复制构造函数时,是否总是需要赋值运算符? - Is assignment operator always necessary when there is a copy constructor? 构造函数引发异常时删除运算符segfaults - Delete operator segfaults when the constructor throws an exception 传递重载运算符的返回值时,为什么不调用复制构造函数 - Why copy constructor is not called when returned value from overloaded operator is passed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM