boost::shared_ptr boost::mutex and copy constructor

送分小仙女□ 提交于 2020-01-04 03:48:50

问题


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
    }
};

I've got the following questions:

  • Is it a bad practice to use the mutex that way (as member of the class, via shared_ptr)?
  • Should I have copy constructor for this class, as it has memory allocated on heap via shared_ptr?

EDIT: 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.


回答1:


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.

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.




回答2:


This approach is pretty valid and legitimate, but note that as your class evolves, you might want to apply the same technique to some more class members. That's why I'd recommend you to consider taking an advantage of pImpl idiom:

// in hpp:
class Sample
{
  Impl();
private:
  struct Impl;
  // compiler generated copy-constructor will copy only this shared_ptr
  shared_ptr<void> pImpl_;
};

// in cpp:
struct Sample::Impl
{
  mutex mut_;
  // put here whatever members you need, extend Impl without affecting the Sample interface
};

Impl::Impl() : pImpl_(new Impl)
{}


来源:https://stackoverflow.com/questions/9483657/boostshared-ptr-boostmutex-and-copy-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!