c++中私有拷贝构造函数有什么用 [英] What's the use of the private copy constructor in c++

查看:31
本文介绍了c++中私有拷贝构造函数有什么用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们为什么要定义私有拷贝构造函数?

Why do people define a private copy constructor?

何时将复制构造函数和赋值运算符设为私有是一个好的设计?

When is making the copy constructor and the assignment operator private a good design?

如果类中没有成员是指向唯一对象(如文件名)的指针或句柄,那么在其他情况下,私有复制构造函数是个好主意吗?

If there are no members in the class which are pointers or handles to a unique object (like file name), then wat other cases are there where private copy constructor is a good idea?

同样的问题适用于赋值运算符.鉴于大多数 C++ 都围绕对象的复制和通过引用传递,是否有涉及私有复制构造函数的好的设计?

Same question apply for assignment operator. Given that majority of C++ revolves around copying of objects and passing by reference, are there any good designs which involve private copy constructor?

推荐答案

某些对象代表不能或不应复制的特定实体.例如,您可能会阻止复制代表应用程序使用的日志文件的对象,这对应于代码的所有部分都将使用单个日志文件的期望.使用意外或不当复制的对象可能会导致日志中出现乱序内容、当前日志大小记录不准确、多次尝试(有些失败)滚动"到新日志文件名或重命名现有文件名.

Some objects represent particular entities that can't or shouldn't be copied. For example, you may prevent copying of an object that represents the log file used by an application, corresponding to the expectation that a single log file will be used by all parts of the code. Use of an accidentally or inappropriately copied object could lead to out-of-order content appearing in the log, inaccurate records of current log size, multiple attempts (some failing) to "roll" to a new log filename or rename the existing one.

另一个用途是通过虚函数强制复制.由于构造函数不能是 virtual,所以通常的做法是防止直接访问复制构造函数并提供一个 virtual Base* clone() 方法,该方法返回指针指向的实际运行时类型.这可以防止 Base b(derived) 出现的意外切片.

Another use is to enforce copying via a virtual function. As constructors can't be virtual, a common practice is to prevent direct access to the copy constructor and provide a virtual Base* clone() method that returns a copy of the actual run-time type to which a pointer points. This prevents the accidental slicing that Base b(derived) would exhibit.

另一个例子:一个死简单的智能指针对象,它只是删除它在构造函数中给出的指针:如果它不支持引用计数或其他处理多个所有者的方式,并且不想冒险意外的 std::auto_ptr 风格的所有权转移,然后简单地隐藏复制构造函数就提供了一个很棒的小智能指针,对于有限的可用情况,它既快速又高效.关于尝试复制它的编译时错误会有效地询问程序员嘿 - 如果你真的想这样做,请将我更改为共享指针,否则退后!".

Another example: a dead-simple smart pointer object that simply deletes the pointer it's given in the constructor: if it doesn't support reference counting or some other manner of handling multiple owners, and doesn't want to have risk awkward unintended std::auto_ptr style transfer of ownership, then simply hiding the copy constructor gives a great little smart pointer that's fast and efficient for the limited cases where it's usable. A compile time error about attempting to copy it would effectively ask the programmer "hey - if you really want to do that change me to a shared pointer, otherwise back off!".

这篇关于c++中私有拷贝构造函数有什么用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆