Copy or Move Constructor for a class with a member

2019-07-06 04:03发布

问题:

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?

回答1:

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.



回答2:

Thanks to Doug's suggestion of using std::unique_ptr, my class is pretty simply now and does what I want. Here's my final solution.

class A
{
private:
    class B
    {
    private:
        std::unique_ptr<std::mutex> mu_ptr = std::make_unique<std::mutex>()
        A* parent = NULL;
    public:
        B(A* const parent_ptr) : parent(parent_ptr) {}
    };
public:
    B b = B(this); // This now works! Great.
};