booster::noncopyable 的用例有哪些?

发布于 2024-09-15 13:00:41 字数 100 浏览 12 评论 0原文

第一:是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等你爱我 2024-09-22 13:00:41

我发现只要你有一个类有一个指针作为该类拥有的成员变量(即负责销毁),它就很有用。除非您使用 shared_ptr<> 或其他引用计数智能指针,否则您无法安全地复制或分配该类,因为在析构函数中您需要删除指针。但是,您不知道是否已获取该类的副本,因此您将因取消引用已释放的指针而导致双重删除或访问冲突。

如果您从 noncopyable 继承,那么它有两个好处:

  • 它可以防止类被复制或分配
  • 通过查看类定义,即自记录代码,可以清楚地表明意图,

例如

class MyClass : boost::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 to delete 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:

  • It prevents the class from being copied or assigned
  • It makes the intention clear from looking at the class definition, ie self-documenting code

eg

class MyClass : boost::noncopyable
{ 
   ...
};
倾城月光淡如水﹏ 2024-09-22 13:00:41

对于 boost 来说,正确的是 boost::noncopyable

正如其名称所示,它用于防止复制对象。当复制导致非常难以处理的情况时,这是有道理的。一个示例是包装文件句柄或网络连接概念的类,如 文档。释放/关闭资源或文件时会出现问题。如果您有很多副本,您将如何处理。您可以使用一些引用计数,但如果您在某些地方展开句柄,则很难正确处理...

就我个人而言,我发现它在实现单例模式中最清晰和有用的用法,在这种情况下您真的只想拥有一个实例,即在这种情况下,您显然不希望被复制。单例确保只能创建一个类的一个实例来保存某些全局资源,例如系统配置。

The right one in the case of boost is boost::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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文