3

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> >'

Al.G.
  • 4,327
  • 6
  • 31
  • 56
user1159517
  • 5,390
  • 8
  • 30
  • 47
  • `DISALLOW_COPY_AND_ASSIGN(A)` should not be a macro that defines the copy ctor and assign operator, it should be a base class that mark the copy and assign operator as deleted, and defaulting move operations. – Guillaume Racicot Oct 10 '17 at 18:50
  • @GuillaumeRacicot, while I always drive from boost noncopyable, I fail to see the advantage of your assertion / axiom above the macro – Werner Erasmus Oct 11 '17 at 08:57

1 Answers1

7

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));
}
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455