jyoung
jyoung

Reputation: 5181

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

Given allocators a1 and a2, where a1 != a2,

and std::vectors v1(a1) and v2(a2)

then v1.swap(v2) invalidates all iterators.

Is this expected behavior?

Upvotes: 11

Views: 1718

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283733

In general, swap never invalidates iterators. 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. 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.

From [container.requirements.general] (wording from 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. 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.

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.

23.3.6.5 does not specify alternate rules for vector::swap().

Upvotes: 17

Related Questions