移动分配的左侧 std::vector 资源会怎样?

What happens to the left hand side std::vector resources on move assignment?

我试图查明 C++ 11 标准是否允许释放接收移动分配的 std::vector 的资源。

我举个例子:

std::vector<int> a {1, 2};
std::vector<int> b {3, 4};
a = std::move(b);

现在我期望的是 ab 都在包装一个常规数组(通常)并且它们有一个指向它的指针,即 a_ptrb_ptr。现在我认为除了其他事情之外,移动分配确实 a_ptr = b_ptr。标准是否保证 a_ptr 中的内存在此之前或之后被释放?

通过查看Table 71: Container requirements,表示容器的内部结构将被破坏。

a = rv => All existing elements of a are either move assigned to or destroyed

正如Howard Hinnant在评论中提到的,有一个特例在上面的句子中也有说明:

All existing elements of a are either move assigned to or destroyed.

这种特殊情况与移动赋值运算符有关,只有 3 种不同的状态:

  1. propagate_on_container_move_assignment 在 lhs 中是 true:

    在这种情况下,lhs 中分配的内存被释放,移动操作完成。分配器也被移动分配。

  2. propagate_on_container_move_assignment在lhs中是false,两边的分配器相等:

    在这种情况下,除了不需要分配给 lhs 分配器外,执行相同的操作序列。

  3. propagate_on_container_move_assignment在lhs中是false,两边的分配器不相等:

    在这种情况下,因为两个分配器不相等,lhs 容器的分配器不能用于管理 rhs 容器的内存,所以唯一的选择是将分配 rhs 容器项目移动到 lhs 容器。

最后一个案例解释了为什么lhs容器中的项目可以移动分配到。在任何情况下,内存都将被释放、重用或重新分配。