不可复制的对象以及复制构造函数和运算符=中的异常
我想让类的对象不可复制,因此我将复制构造函数和运算符=放在私有部分中。然而,一个类是该类的友元,因此它可以访问私有方法。在复制构造函数和运算符=中放置抛出异常以确保对象不会被复制是个好主意吗?
I'd like to make object of class not copyable so I put copy constructor and operator= in private section. However one class is friend of this class so it has access to private methods. Is it good idea to put throw exception in copy constructor and operator= to be sure that object will not be copied?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使其不可复制的一种方法是仅声明复制构造函数,但根本不实现它。如果有人尝试使用它,这将在编译时强制出现链接器错误。
One approach to make it not copyable is just to declare the copy constructor, but don't implement it at all. That will force a linker error at compile time if anyone tries to use it.
@Mysticial 已经回答了这个问题,通常是在 C++03 中完成的。但在 C++11 中,您可以做得更好:
=delete
传达foo
不支持复制语义的消息,因为它已被禁用通过用delete
显式标记它。我在这里详细解释了这一点:@Mysticial have answered this question which is usually done in C++03. But in C++11, you can do this, more nicely:
The
=delete
conveys the message thatfoo
doesn't support copy-semantic, as it has been disabled by explicitly marking it withdelete
. I've explained this in detail here: