user997112
user997112

Reputation: 30615

Assign std::vector<std::unique_ptr<T>> to another std::vector<std::unique_ptr<T>>

I have a std::vector<std::unique_ptr<MyClass>> and I am assigning this to a second vector of the same type.

I am getting this compiler error:

/opt/gcc-8.2.0/include/c++/8.2.0/bits/stl_algobase.h:324:18: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>& std::unique_ptr<_Tp, _Dp>::operator=(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = MyClass; _Dp = std::default_delete<MyClass>]'
        *__result = *__first;

Is this because in order to do the assignment, I need to define a move assignment operator for MyClass? The class only contains a couple of unordered_maps, a set and a couple of primitives. No pointer members.

Upvotes: 2

Views: 261

Answers (2)

SergeyA
SergeyA

Reputation: 62583

You cannot copy-assign a vector of std::unique_ptr elements to another, because you cannot copy std::unique_ptr itself. It is unique!

No operations defined on your MyClass can change this fact.

You can move from such a vector, though - but that means the original vector will no longer hold those std::unique_ptr elements.

Upvotes: 8

Nikos C.
Nikos C.

Reputation: 51840

unique_ptr, as the name suggests, is not copyable. Only one instance can exist. As a result, you can't copy a vector containing unique_ptr elements, since they can't be copied from one vector to another. You can only move one vector to another:

dest_vector = std::move(src_vector);

src_vector can't be used after that (other than moving something new into it.) All the elements it contains have moved into dest_vector.

If you actually want copies, then use shared_ptr instead. Each copy will still manage the same pointer and will keep track of how many copies exist. The managed pointer will only be deleted once all shared_ptr copies have been destroyed.

Upvotes: 3

Related Questions