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.