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?
CodePudding user response:
Are they exactly the same?
No, They are not!
The first one invokes the move constructor of the std::map
4 and the move operation will be done at class/ data structure level.
[...]
- Move constructor. After container move construction (
overload (4)
), references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in*this
. The current standard makes this guarantee via the blanket statement in container.requirements.general, and a more direct guarantee is under consideration via LWG 2321
Complexity
4) Constant. If alloc is given and
alloc != other.get_allocator()
, then linear.
The second std::move
is from <algorithm>
header, which does element wise(i.e. key value pairs) movement to the other map.
- Moves the elements in the range
[first, last)
, to another range beginning atd_first
, starting from first and proceeding to last - 1. After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move.
Complexity
Exactly
last - first
move assignments.
CodePudding user response:
No, they are not the same.
- Case 1 moves the content of the whole
map
at once. Themap
's internal pointer(s) are "moved" tomp2
- none of thepair
s in the map are affected. - Case 2 moves the individual
pair
's in the map, one by one. Note thatmap
Key s areconst
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.