Search code examples
classmutexcopy-constructormembermove-constructor

Copy or Move Constructor for a class with a member std::mutex (or other non-copyable object)?


class A
{
private:
    class B
    {
    private:
        std::mutex mu;
        A* parent = NULL;
    public:
        B(A* const parent_ptr): parent(parent_ptr) {}
        B(const A::B & b_copy) { /* I thought I needed code here */  }
    };
public:
    B b = B(this); //...to make this copy instruction work. 
                   // (Copy constructor is deleted, need to declare a new one?)
};

I have a class B that is basically a thread-safe task queue. It contains a deque, a mutex, and a condition_variable. It facilitates a consumer/producer relationship between any two threads that are started by the class A. I have simplified the code as much as possible.

The problem starts with having a mutex as a member: this deletes the default copy constructor. This just means I can construct using B(this) but I am not able to construct and copy using B b = B(this), which is what I need to do in the last line in order to give class A members of class B. What is the best way to solve this problem?


Solution

  • The simple solution is to use a std::unique_ptr<std::mutex> in your class, and initialize it with std::make_unique(...) where ... are your std::mutex constructor arguments, if any.

    This will allow for move but not copy. To make it copyable, you would need to initialize the copy in the copy constructor, assuming copies should have their own lock.

    If copies should share that lock, then you should use a std::shared_ptr. That is copyable and movable.