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

橙三吉。 提交于 2019-12-10 19:57:28

问题


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.
};


来源:https://stackoverflow.com/questions/37172050/copy-or-move-constructor-for-a-class-with-a-member-stdmutex-or-other-non-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!