Search code examples
c++c++11movemove-semanticsunique-ptr

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.


Solution

  • 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.