复制或移动具有成员std :: mutex(或其他不可复制对象)的类的构造函数? [英] Copy or Move Constructor for a class with a member std::mutex (or other non-copyable object)?

查看:642
本文介绍了复制或移动具有成员std :: mutex(或其他不可复制对象)的类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?)
};

我有一个类B,它基本上是一个线程安全的任务队列.它包含一个deque,一个mutex和一个condition_variable.它促进了由类A启动的任何两个线程之间的消费者/生产者关系.我已尽可能简化了代码.

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.

问题开始于拥有mutex作为成员:这会删除默认的副本构造函数.这只是意味着我可以使用B(this)构造,但是我不能使用B b = B(this)构造副本,这是我在最后一行中要做的,以便提供类A B类的成员.解决此问题的最佳方法是什么?

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?

推荐答案

简单的解决方案是在类中使用std::unique_ptr<std::mutex>,并使用std::make_unique(...)对其进行初始化,其中...是您的std::mutex构造函数参数,如果有的话.

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.

如果副本应共享该锁,则应使用std::shared_ptr.那是可复制和可移动的.

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

这篇关于复制或移动具有成员std :: mutex(或其他不可复制对象)的类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆