jeudi 11 mars 2021

How to enqueue each element in a vector of unique pointers? (C++)

I'm trying to push each element of a vector of unique pointers into a queue, but for some reason my code won't compile.

The error I'm getting is: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Foo; _Dp = std::default_delete<Foo>]’.

Since I'm moving the vector of unique pointers into the enqueue function, and again moving each element into queue_, I'm not sure why this isn't working.

#include <memory>
#include <vector>
#include <queue>

class Foo {};

class Bar {
  
 public:
  template<typename Container>
  void enqueue(Container c) {
    for (const auto &e : c) {
      queue_.push(std::move(e));
    }
  };
  
 private:
  std::queue<std::unique_ptr<Foo>> queue_;
};

int main() {

  Bar bar;

  std::vector<std::unique_ptr<Foo>> c;
  c.push_back(std::make_unique<Foo>());

  bar.enqueue(std::move(c)); // this line is causing problem

};

Aucun commentaire:

Enregistrer un commentaire