boost :: shared_ptr boost :: mutex和复制构造函数 [英] boost::shared_ptr boost::mutex and copy constructor

查看:431
本文介绍了boost :: shared_ptr boost :: mutex和复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要保护对班级中数据结构的访问.由于我无法使用互斥锁(因为无法复制它),因此我正在考虑使用shared_ptr并将互斥锁保留在此处.这是我的想法的示例代码:

I need to protect the access to a data structure in my class. As I can't have mutex (because I can't copy it) I am considering to have shared_ptr and keep the mutex there. Here is a sample code of my idea:

class Sample {
    typedef boost::lock_guard<boost::mutex> AcquireLock;
    boost::shared_ptr<boost::mutex> mutt;

public:
    Sample() : mutt(new boost::mutex) {}

    void Method()
    {
        AcquireLock lock(*mutt);

        //do some work here
    }
};

我有以下问题:

  • 以这种方式(通过shared_ptr作为类的成员)使用互斥体是一种不好的做法吗?
  • 我是否应该为此类提供复制构造函数,因为它通过shared_ptr在堆上分配了内存?

也许我需要提供更多详细信息: 我将只创建一次该对象,并将其保存在std :: vector中.我不需要复制它,如果矢量需要复制,我不想为每个复制使用不同的互斥量.这就是为什么我认为复制构造函数将对我有用.

Maybe I need to give a bit more details: I'll create this object only once and save it in std::vector. I don't need to make copies of it and if the vector needs to make copies, I don't want to have different mutex for each copy. That's why I think the copy constructor will work for me.

推荐答案

如果创建Sample对象的副本,则将调用副本构造函数,该副本构造函数是由编译器自动生成的,或者是您已明确编写的.

If you make a copy of a Sample object, the copy constructor will be called, either one generated automatically by the compiler, or one that you have written explicitly.

允许Sample对象的副本是否是一个好主意取决于您要执行的操作. 如果允许复制没有意义,则将对象设为不可复制,例如通过为副本构造函数提供私有原型.

Whether it's a good idea to allow copies of Sample objects depends on what you are trying to do. If it doesn't make sense to allow copies, then make the object non-copyable, e.g. by giving a private prototype for the copy constructor.

如果确实要允许副本,则需要确定每个副本是否应具有其自己的互斥体,并适当地定义副本构造函数.自动生成的副本构造函数将仅执行浅表副本,因此所有副本都将共享互斥体.

If you do want to allow copies, then you need to decide if each copy should have its own mutex, and define the copy constuctor appropriately. The automatically generated copy constructor will only do a shallow copy, so all copies would share the mutex.

这篇关于boost :: shared_ptr boost :: mutex和复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆