Search code examples
c++c++11movestdmapstd

Move a std::map vs move all the elements of a std::map


std::map<int, Obj> mp;
// insert elements into mp

// case 1
std::map<int, Obj> mp2;
mp2 = std::move(mp);

// case 2
std::map<int, Obj> mp3;
std::move(std::begin(mp), std::end(mp), std::inserter(mp3, std::end(mp3));

I am confused by the two cases. Are they exactly the same?


Solution

  • No, they are not the same.

    • Case 1 moves the content of the whole map at once. The map's internal pointer(s) are "moved" to mp2 - none of the pairs in the map are affected.
    • Case 2 moves the individual pair's in the map, one by one. Note that map Key s are const so they can't be moved but will instead be copied. mp will still contain as many elements as before - but with values in an indeterminable state.