简体   繁体   English

带有状态分配器的 std::vector::swap() 是否应该使所有迭代器无效?

[英]Should std::vector::swap() with stateful allocators invalidate all iterators?

Given allocators a1 and a2 , where a1 != a2 ,给定分配器a1a2 ,其中a1 != a2

and std::vector s v1(a1) and v2(a2)std::vector s v1(a1)v2(a2)

then v1.swap(v2) invalidates all iterators.然后v1.swap(v2)使所有迭代器无效。

Is this expected behavior?这是预期的行为吗?

In general, swap never invalidates iterators.通常, swap永远不会使迭代器无效。 However, another rule comes into play when the allocators are different.然而,当分配器不同时,另一个规则就会发挥作用。 In that case the behavior depends on allocator_traits<a1>::propagate_on_container_swap::value and allocator_traits<a2>::propagate_on_container_swap::value .在这种情况下,行为取决于allocator_traits<a1>::propagate_on_container_swap::valueallocator_traits<a2>::propagate_on_container_swap::value If both are true, the allocators are exchanged along with the data, all iterators remain valid.如果两者都为真,则分配器与数据一起交换,所有迭代器保持有效。 If either is false, behavior is undefined, so the particular behavior exhibited by VC++ 2010 is allowed.如果其中一个为假,则行为未定义,因此允许 VC++ 2010 展示的特定行为。

From [container.requirements.general] (wording from n3290):来自[container.requirements.general] (措辞来自 n3290):

Allocator replacement is performed by copy assignment, move assignment, or swapping of the allocator only if allocator_traits<allocatortype>::propagate_on_container_copy_assignment::value , allocator_traits<allocatortype>::propagate_on_container_move_assignment::value , or allocator_traits<allocatortype>::propagate_on_container_swap::value is true within the implementation of the corresponding container operation.仅当allocator_traits<allocatortype>::propagate_on_container_copy_assignment::valueallocator_traits<allocatortype>::propagate_on_container_move_assignment::valueallocator_traits<allocatortype>::propagate_on_container_swap::value时,分配器替换通过分配器的复制分配、移动分配或交换来执行allocator_traits<allocatortype>::propagate_on_container_swap::value为 true 时执行相应的容器操作。 The behavior of a call to a container's swap function is undefined unless the objects being swapped have allocators that compare equal or allocator_traits<allocatortype>::propagate_on_container_swap::value is true.调用容器的交换 function 的行为是未定义的,除非被交换的对象具有比较相等或allocator_traits<allocatortype>::propagate_on_container_swap::value为 true 的分配器。

and

Every iterator referring to an element in one container before the swap shall refer to the same element in the other container after the swap在交换之前引用一个容器中的元素的每个迭代器都应该在交换之后引用另一个容器中的相同元素

and

Unless otherwise specified... no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped.除非另有说明... no swap() function 使任何引用被交换容器元素的引用、指针或迭代器无效。

23.3.6.5 does not specify alternate rules for vector::swap() . 23.3.6.5 没有为vector::swap()指定替代规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM