在c ++中私有副本构造函数的用途是什么 [英] What's the use of the private copy constructor in c++

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

问题描述

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

Why do people define a private copy constructor?

何时使拷贝构造函数和赋值运算符成为一个好的设计?

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

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

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() code>方法返回指针指向的实际运行时类型的副本。这可以防止 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天全站免登陆