Since C++11, you can use the move assignment semantics instead. All containers provide move assignment operators (array<> implicitly again), declared for rvalues, which internally just swap pointers to the memory of values rather than copying all values. The exact behavior is not specified, but the guarantee of constant complexity for this operation leads to an implementation like this. The C++ standard library simply specifies that after a move assignment, the container on the left hand side of the assignment has the elements that the container on the right hand side of the assignment had before. The contents of the container on the right hand side are undefined afterward:
So, for performance reasons, you should use this way of assignmentif after the assignment, the contents of the container on the right hand side are no longer used. - 'The C++ Standard Library: A Tutorial and Reference' by Nicolai M. Josuttis |
v2 = std::move(v1) ;
may be implemented as: std::swap(v1,v2) ;