移动 std::map 与移动 std::map 的所有元素

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));

我对这两种情况感到困惑。它们完全一样吗?

不,它们不一样。

  • 案例 1 一次移动整个 map 的内容。 map 的内部指针被“移动”到 mp2 - 地图中 pair 的 none 受到影响。
  • 案例 2 将地图中的个体 pair 一一移动。请注意 map Keyconst 所以它们不能被移动,而是被复制。 mp 仍将包含与以前一样多的元素 - 但值处于不确定状态。

Are they exactly the same?

没有,他们不是!

第一个调用std::map4移动构造函数,移动操作将在class/数据结构层级.

[...]

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


第二个 std::move 来自 <algorithm> header,它按元素(即键值对)移动到另一个映射。

  1. Moves the elements in the range [first, last), to another range beginning at d_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.