为什么我要将复制构造函数和赋值运算符设为私有并在 C++ 中实现?
受到这个问题的启发。
通常将复制构造函数和赋值运算符设置为私有的原因是为了使类不可复制 这样对象只能被创建和销毁,而不能被复制——大多数时候是因为复制它们是没有意义的。在这种情况下,复制构造函数和赋值运算符都被设为私有
并且未实现 - 如果该类不可复制,则任何人都不应复制。
是否存在复制构造函数和赋值运算符需要私有并同时具有有意义的实现的情况?
Inspired by this question.
Usually the reason to make copy-constructor and assignment operator private
is to make the class non-copyable so that objects can only be created and destroyed, but not copied - most of the times it is because copying them would make no sense. In such cases the copy constructor and the assignment operator are both made private
and not implemented - if the class is not copyable then noone should copy.
Is there a case when copy constructor and assignment operator need to be private
and have meaningful implementation at the same time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我立即想到两种情况:
朋友
s:假设,作为设计的一部分,您有两个高度耦合的类,其中一个类需要能够复制另一个类(例如,在工厂模型或类似的模型中),但您不想让全世界都可以复制它。
包装:
假设您希望能够有条件地克隆某些元素,具体取决于某些内部行为(例如,取决于某些类状态条件) - 从语言角度来看,最干净的方法 - 仍然是将复制分离为自己的元素功能。这将允许很好地分离关注点。
There are two cases that come to mind immediately:
friend
s:Say that, as part of your design, you have two highly coupled classes where one needs to be able to copy the other (say, as in a factory model or some such), but you don't want to let the whole world be able to copy it.
wrappers:
Say you want to be able to conditionally clone some element, depending on some internal behavior (e.g., depending on some class-stateful condition) - the cleanest way, from a language perspective - is still to separate the copying into its own function. This would allow for good separation of concerns.
我的猜测是,这对于持有自身列表的类很有用 - 然后它可以在内部复制实例。这实际上只对既是项目又是容器的类有用:
另一个想法是允许在类控制的情况下进行克隆。当复制有意义时这可能很有用,但仅限于特定条件或权限:
My guess is that this can be useful for a class that is holding a list of itself - then it can copy the instances internally. This is really only useful for a class that is both the item and the container:
Another thought is to allow cloning in circumstance controlled by the class. This might be useful when copying can make sense, but only on specific conditions or permissions:
朋友
无法对其进行任何访问。如果你实现了,就意味着您希望
朋友
能够访问。这是一个设计决定。使其代码看起来“肮脏”(类似于 C++ 风格的转换)
操作,显示代码中的污垢)
例如
我们已经放置了这个包装< code>clone() 允许用户进行克隆,但它也明确显示他/她正在做什么。
operator =
unimplemented so that evena
friend
cannot have any access to it. If you implement, it meansyou want a
friend
to have access. This is a design decision.make its code "dirty" looking (something like C++ style casting
operations, which shows dirt in your code)
e.g.
We have put this wrapper
clone()
to allow the user for cloning, however it also displays explicitly what exactly he/she is doing.