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.
std::mutex::mutexmutex objects cannot be copied/moved (both the copy constructor and assignment operator are deleted for this type).
std::mutex is neither copyable nor movable.
On the other hand, while right now std::mutex is not movable, it is very easy to 'return' one from a function: return an std::unique_ptr<std::mutex> instead. This still pays the costs of dynamic allocation but only in one spot.
Mutexes can be fair or unfair. A fair mutex lets threads through in the order they arrived. Fair mutexes avoid starving threads.
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. 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With