4165. Should swapping a built-in array or std::array with itself result in UB?

Section: 18.4.9 [concept.swappable], 22.2.2 [utility.swap], 23.3.3.3 [array.members] Status: New Submitter: Jiang An Opened: 2024-10-13 Last modified: 2024-10-13

Priority: Not Prioritized

View other active issues in [concept.swappable].

View all other issues in [concept.swappable].

View all issues with New status.

Discussion:

Currently, the std::swap overload for built-in arrays, the swap member function of std::array, the std::swap overload for std::array, and the expression-equivalent-to operation of std::ranges::swap for built-in arrays are specified to be equivalent to performing std::(ranges::)swap_ranges. As swap_ranges functions require that the swapped ranges shall not overlap (26.7.3 [alg.swap]/2), swapping a built-in array or a nonzero-length std::array with itself results in undefined behavior.

It seems that no other swap operation in the standard library has precondition that both arguments don't refer to the same object. Should we make self-swapping of arrays well-defined? If so, perhaps we should change the semantics to plain loops that execute swap or ranges::swap on elements.

Proposed resolution: