Search code examples
c++boostmutexshared-ptrcopy-constructor

boost::shared_ptr boost::mutex and copy constructor


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.


Solution

  • 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.