如何为没有复制构造函数的对象分配索引

How to assign objects with an index that don't have a copy constructor

我正在使用此处的并发队列:

https://github.com/cameron314/readerwriterqueue

基本上只有一个生产者,它为多个消费者生产数据。 每个消费者都应该有自己的队列,每个消费者都有一个唯一的标识符。

理想情况下,我想将队列添加到 std::map 并将唯一标识符映射到队列。

不幸的是,这不起作用,因为队列实现没有复制构造函数,因此拒绝添加到映射中。

如何将唯一 ID 映射到队列?

潜在的问题是队列不允许复制或移动在这种情况下,解决方案是使用 std::unique_ptr,它可以为您提供一个非常安全的解决方案来创建这些对象堆。关键是这个类型只能移动,不能复制。

根据您的描述,我想您会想要创建一个 std::map<unsigned int, std::unique_ptr<ReaderWriterQueue<T>>>

class SomeClass
{
   public:
   void setUpQueue(unsigned int new_id)
   {
      std::unique_ptr<ReaderWriterQueue<T>> ptr(new ReaderWriterQueue<T>(...)); 
      // Have to use move here, othrewise, it would attempt to make a copy
      queue_map.emplace(new_id, std::move(ptr));    
      // could also do
      // queue_map.insert({new_id, std::move(ptr)}; or
      // queue_map.insert(std::make_pair(new_id, std::move(ptr));
   }

   std::map<unsigned int, std::unique_ptr<ReaderWriterQueue<T>>> queue_map;
}