booster::noncopyable 的用例有哪些?
第一:是 boost::noncopyable 还是 booster::noncopyable。我在不同的地方都见过。
为什么要让一个类不可复制?您能提供一些示例用例吗?
First: is it boost::noncopyable or booster::noncopyable. I have seen both in different places.
Why would one want to make a class noncopyable? Can you give some sample use cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我发现只要你有一个类有一个指针作为该类拥有的成员变量(即负责销毁),它就很有用。除非您使用
shared_ptr<>
或其他引用计数智能指针,否则您无法安全地复制或分配该类,因为在析构函数中您需要删除指针。但是,您不知道是否已获取该类的副本,因此您将因取消引用已释放的指针而导致双重删除或访问冲突。
如果您从
noncopyable
继承,那么它有两个好处:例如
I find it useful whenever you have a class that has a pointer as a member variable which that class owns (ie is responsible for destroying). Unless you're using
shared_ptr<>
or some other reference-counted smart pointer, you can't safely copy or assign the class, because in the destructor you will want todelete
the pointer. However, you don't know if a copy of the class has been taken and hence you'll get either a double-delete or access violation from dereferencing a freed pointer.If you inherit from
noncopyable
then it has two benefits:eg
对于
boost
来说,正确的是boost::noncopyable
。正如其名称所示,它用于防止复制对象。当复制导致非常难以处理的情况时,这是有道理的。一个示例是包装文件句柄或网络连接概念的类,如 文档。释放/关闭资源或文件时会出现问题。如果您有很多副本,您将如何处理。您可以使用一些引用计数,但如果您在某些地方展开句柄,则很难正确处理...
就我个人而言,我发现它在实现单例模式中最清晰和有用的用法,在这种情况下您真的只想拥有一个实例,即在这种情况下,您显然不希望被复制。单例确保只能创建一个类的一个实例来保存某些全局资源,例如系统配置。
The right one in the case of
boost
isboost::noncopyable
.It is used to prevent copying of objects like the name tells. It makes sense where copying leads to a very difficult to handle situation. An example is a class wrapping the concept of file handle or network connection like stated in the documentation. The problems arise with freeing/closing the resource or file. If you have many copies of them how would you handle it. You could use some reference counting but it is difficult to handle correctly if you unwrap the handles at some places...
Personally I find its most clear and useful usage in implementing a singleton pattern, where you really want to have only one instance, that in this case you obviously do not want to be copyable. Singletons ensure only one instance of a class can be created for holding some global resources for example a system configuration.