Copy class using std :: mutex

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

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

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

Obviously this is not possible since the mutex object is not copied. The way to solve it is through the copy constructor.

However, I had a problem creating a copy constructor. I tried

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

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

I am not sure which is the correct syntax of the three options. Please, help.

+10
source share
5 answers

Short answer: you do not copy mutexes.

, mutex - , , , , , / . / , .

. .

+8

. :

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

, mutex m - default initialized, , . .

. m x, :

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

m ( c const copy ctor).

mutable std::mutex m;

, , c , , , .

+8

shared_ptr<C>, C ...

+4

std:: mutex m . .

+1

, , , , , , , , . , ( ) (.. ). , , , , ( ?) .

Here is a complete example to help someone in the future run into this problem:

class Shape
{
public:
    Shape() {} //default constructor
    Shape(double _size) //overloaded constructor
    {
        size = _size;
    }

    Shape(const Shape& obj) //copy constructor (must be explicitly declared if class has non-copyable member)
    {
        //Do not put any non-copyable member variables in here (ie the mutex), as they will be
        //default initialized if left out

        size = obj.size; //any variables you want to retain in the copy
    }
    Shape& operator=(const Shape&& obj) //move constructor (must be explicitly declared if class has non-copyable member)
    {
        //Do not put any non-copyable member variables in here (ie the mutex), as they will be
        //default initialized if left out

        size = obj.size;//any variables you want to retain in the move
        return *this;
    }

    double testMe() { return size; }
private:
    std::mutex dataMutex;
    double size;
};
0
source

Source: https://habr.com/ru/post/1588921/


All Articles