CKTIS / C++
std::swap — exchanging values
std::swap from <utility> exchanges the values of two objects and returns void. Learn the primary template's requirements, the array overload, and the call pattern that enables ADL in generic code.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <utility>
std::swap(a, b);
// Generic code with argument-dependent lookup:
using std::swap;
swap(a, b);std::swap(a, b) from <utility> exchanges the values of the objects referred to by its arguments; it returns void. The primary template takes both arguments through T&, so they must match the same type T.
The primary template requires T to meet Cpp17MoveConstructible and Cpp17MoveAssignable. Its exception specification corresponds to noexcept(is_nothrow_move_constructible_v<T> && is_nothrow_move_assignable_v<T>); do not assume every swap is non-throwing.
A separate overload handles built-in arrays with the same element type and length, exchanging corresponding elements. The elements must be swappable with one another.
In generic code, use using std::swap; swap(a, b);. This allows both the standard templates and a swap function found through argument-dependent lookup (ADL). A qualified call to std::swap(a, b) does not perform ADL.
This entry targets C++23. The supplied standard draft is a living document, not a frozen C++23 publication; this entry does not attest a production runtime.
Examples
#include <iostream>
#include <utility>
int main() {
int a = 3;
int b = 8;
std::swap(a, b);
std::cout << a << ' ' << b << '\n';
}
Result
8 3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.