c++c++11

Copy Class with std::mutex


I have a class with a std::mutex as a member. I am trying to create an array of such class

class C
{
 int x;
 std::mutex m;
};

int main()
{
  C c[10];
  //later trying to create a temp C
  C temp = c[0];
}

Clearly the above is not possible as mutex object is not copyable. The way to solve it is through a copy constructor.

However, I am having problem in creating a copy constructor. I have tried

C (const C &c)
{
   x = c.x;

   //1. m
   //2. m()
   //3. m = c.m
}

I am not sure what is the right syntax out of the 3 choices. Please help.


Solution

  • Short answer: you don't copy the mutex.

    Lets start from the basics. Mutex is a short name for mutual exclusion, i.e you want to make sure that, when there are multiple threads you don't want them to change/modify the value in parallel. You want to serialize the access or modification/read so that the value read is valid.

    In this case you are copying a new value to the variable; you need not use a mutex lock as you are creating a new object.