Copy Class with std::mutex

You shouldn't write any of these lines. Your implementation of copy constructor is equivalent to:

C (const C &c) : x(), m()
{
   x = c.x;
}

So new instance of mutex m is default initialized which means that one of the default constructors will be called. It may be safely used.

However, there are several conserns about this code. I.e. if m protects x, you should explicitly lock it before accessing value:

C (const C &c)
{
    std::lock_guard<std::mutex> (c.m);
    x = c.x;
}

which would require to declare m as mutable (because c is const reference in copy ctor).

mutable std::mutex m;

In the end, you can see that copying objects with mutexes inside is confusing, and if C is public class, it'll confuse its users, so think twice before implementing copying of it.


Short answer you dont copy the mutex.

Lets start from the basics, mutex is a short name of mutual exclusion i.e you want to make sure that, when there are multiple threads you dont 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 the above case you are copying a new value to the variable.In this case you need not use a mutex lock as you are creating a new object.


You could use an array of shared_ptr<C>, then you won't need C itself to be copyable...

Tags:

C++

C++11