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
。我已经尽可能简化了代码。
问题始于拥有amutex
作为成员:这将删除默认的副本构造函数。这仅仅意味着我可以构造使用,B(this)
但是我不能构造和复制使用B b = B(this)
,这是我在最后一行中要做的,以便给class的类A
成员B
。解决此问题的最佳方法是什么?
一种简单的解决方案是std::unique_ptr<std::mutex>
在您的类中使用a ,并使用构造函数参数(如果有)std::make_unique(...)
在哪里对其...
进行初始化std::mutex
。
这将允许移动,但不能复制。为了使其可复制,您需要在副本构造函数中初始化副本,并假设副本应具有自己的锁。
如果副本应共享该锁,则应使用std::shared_ptr
。那是可复制和可移动的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句