【问题标题】:Copy or Move Constructor for a class with a member std::mutex (or other non-copyable object)?为具有成员 std::mutex (或其他不可复制对象)的类复制或移动构造函数?
【发布时间】:2016-05-11 19:50:35
【问题描述】:
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 启动的任意两个线程之间的消费者/生产者关系。我已经尽可能地简化了代码。

问题始于将mutex 作为成员:这会删除默认的复制构造函数。这只是意味着我可以使用B(this) 构造,但我无法使用B b = B(this) 构造 副本,这是我在最后一行中需要做的,以便给A 上课班级B 的成员。解决此问题的最佳方法是什么?

【问题讨论】:

    标签: class mutex copy-constructor member move-constructor


    【解决方案1】:

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

    这将允许移动但不允许复制。为了使其可复制,您需要在复制构造函数中初始化副本,假设副本应该有自己的锁。

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

    【讨论】:

      【解决方案2】:

      感谢 Doug 对使用 std::unique_ptr 的建议,我的课程现在非常简单,可以做我想做的事。这是我的最终解决方案。

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

      【讨论】:

        猜你喜欢
        • 2020-10-03
        • 2013-03-27
        • 2011-11-25
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        • 1970-01-01
        • 2015-08-18
        • 1970-01-01
        相关资源
        最近更新 更多