How to create a vector with non-copyable and non-assignable objects?

1.5k Views Asked by At

I have a class

class A {
 public:
  A(int x): x_(x) {}
  void SetValue(int m) {x_=m};
 private:
   DISALLOW_COPY_AND_ASSIGN(A);
};

I'm trying to create a vector of objects of type A

vector<std::unique_ptr<A>> objects;
objects.reserve(10);
for (int i = 0; i < 10; i++) {
   auto a = MakeUnique<A>();
   a->SetValue(20);
   objects.emplace_back(a);
}

This results in a compilation error call to deleted constructor of 'std::unique_ptr<A, std::default_delete<A> >'

1

There are 1 best solutions below

4
On BEST ANSWER

std::unique_ptr is not copyable, so you need to move it into the container:

for (int i = 0; i < 10; i++) {
   auto a = MakeUnique<A>();
   a->SetValue(20);
   objects.emplace_back(std::move(a));
}