1

I want to replace the unique_ptr object at that index with another one, which is essentially "deleting" the pointer currently in the vector, and moving classObj into that spot.

std::unique_ptr<ClassName> classObj(new className());
classNameStorage[5] = classObj; // classNameStorage.size() > 5

The code above, using the assignment operator is invalid.

wpakt
  • 1,073
  • 2
  • 13
  • 18
  • Possible duplicate of [Why can I not push\_back a unique\_ptr into a vector?](http://stackoverflow.com/questions/3283778/why-can-i-not-push-back-a-unique-ptr-into-a-vector) – Brian Rodriguez Dec 08 '15 at 22:43
  • On an aside note, the first line can be expressed as `auto classObj = std::make_unique()`. According to Scott Meyers, the advantage of `std::make_unique` (other than having less to type) is that it ensures that the `unique_ptr` takes ownership immediately upon instantiation of `T`. This makes a difference in more complex expressions and in the presence of exceptions. A compiler is allowed to evaluate `x(std::unique_ptr(new T), y())` by first evaluating `new T`, then `y()`, and then the `unique_ptr` constructor on the former. In such case, a throw from `y()` will leak a `T`. – user4815162342 Dec 08 '15 at 22:43
  • What is the type of classNameStorage? – Martin York Dec 08 '15 at 23:59

1 Answers1

5

classNameStorage[5] = std::move(classObj);

std::unique_ptr is a move-only class. Thus, in situations where an instance has a name (i.e. is an lvalue), you must wrap it in std::move ("convert" into an rvalue) to have the data moved out.

See here for more details.

Community
  • 1
  • 1
Brian Rodriguez
  • 4,250
  • 1
  • 16
  • 37