In generic C++ code, why write using std::swap; swap(a, b); instead of std::swap(a, b), and what does C++20's std::ranges::swap change?
answer
- qualified calls skip ADL
- std::swap as the fallback
- the type's own cheap swap
- a customization point object
basics
~20 sA qualified std::swap(a, b) never sees a type's own cheaper swap. The two-step keeps std::swap as a fallback and lets argument-dependent lookup find a swap declared beside the type. C++20's std::ranges::swap does that lookup for you.
solid answer
~40 sMany types provide a cheaper or non-throwing `swap` in their own namespace, for example one that exchanges internal buffers. `std::swap(a, b)` is a **qualified** call, so argument-dependent lookup never runs and the generic move-based `std::swap` is used. Writing `using std::swap;` and then an unqualified `swap(a, b)` puts `std::swap` in the overload set as a fallback for `int` and standard types, while ADL adds any `swap` from the argument type's namespace, which wins when it is a better match. The standard's own Swappable requirements are phrased in exactly this context. C++20 adds `std::ranges::swap`, a **customization point object** that performs the unqualified, ADL-based call itself and falls back to a move-based exchange, so generic code can write one qualified call and still reach the type's own `swap`.
code
cpp · 32 lines#include <concepts>
#include <iostream>
#include <utility>
#include <vector>
namespace geo {
struct Polygon {
std::vector<double> xs, ys;
};
// Cheap, non-throwing swap: exchanges the vectors' buffers.
void swap(Polygon& a, Polygon& b) noexcept {
std::cout << "geo::swap\n";
a.xs.swap(b.xs);
a.ys.swap(b.ys);
}
} // namespace geo
template <class T>
void reorder(T& a, T& b) {
using std::swap; // fallback for int, double, std types
swap(a, b); // unqualified: ADL can find geo::swap
}
int main() {
geo::Polygon p{{0, 1}, {0, 1}}, q{{2}, {2}};
std::swap(p, q); // qualified: the custom swap is never considered
reorder(p, q); // prints geo::swap
std::ranges::swap(p, q); // C++20 customization point: also finds geo::swap
int i = 1, j = 2;
reorder(i, j); // falls back to std::swap
std::cout << i << j << '\n';
}go deeper
Recall that a type can provide its own swap and that generic code should write using std::swap; followed by an unqualified swap(a, b).
Explain why: a qualified call skips argument-dependent lookup, the using-declaration supplies the fallback, and overload resolution prefers the exact non-template match from the type's namespace.
Show you know the edges: never extend namespace std, keep the custom swap noexcept, and use std::ranges::swap in C++20 code so generic algorithms reach the type's swap with one qualified call.
Set the convention for a codebase: where customization functions live, whether new code uses the C++20 customization point objects, and how generic utilities call them so user types plug in reliably.
## Why a type writes its own swap The generic `std::swap(T& a, T& b)` from `<utility>` does three moves: move `a` into a temporary, move `b` into `a`, move the temporary into `b`. For many types that is fine. For others a dedicated `swap` is better: - A type holding several buffers can exchange them pointer by pointer, which is cheap and cannot throw. - A type whose move operations are expensive or missing can still be swapped member by member. - Copy-and-swap assignment and many algorithms rely on a `noexcept` swap for their exception guarantees. The convention is to declare that `swap` as a non-member in the **same namespace as the type**, or as a hidden friend inside the class, so that argument-dependent lookup can find it. ## What each spelling finds | Call in generic code | Lookup | Custom `geo::swap` used? | Works for `int`? | |---|---|---|---| | `std::swap(a, b)` | qualified: only `std` | never | yes | | `swap(a, b)` alone | ordinary + ADL | yes | no, unless some other `swap` is visible | | `using std::swap; swap(a, b);` | `std::swap` made visible, plus ADL | yes, when it is the better match | yes | | `std::ranges::swap(a, b)` (C++20) | the object performs ADL itself | yes | yes | A **qualified** name never triggers argument-dependent lookup, so `std::swap(a, b)` silently ignores `geo::swap`. A lone unqualified `swap(a, b)` finds `geo::swap` through ADL but fails for `int`, because fundamental types have no associated namespace. The two-step combines both: the using-declaration makes the `std` templates candidates, ADL adds the type's own overload, and overload resolution prefers the non-template, exactly matching `geo::swap(Polygon&, Polygon&)` over the `std::swap` template. ## The standard writes it the same way The library's **Swappable requirements** define "swappable with" in terms of an unqualified call `swap(t, u)` evaluated in a context whose candidate set includes the two `swap` function templates from `<utility>` and the result of argument-dependent lookup. The example right below that definition is a function template that does `using std::swap;` and then `swap(t1, t2);`. When a standard algorithm needs to swap elements of your type, it uses this context, so your `swap` should be findable by ADL. ## Where the custom swap must not go Do not add an overload of `swap` to namespace `std`. The standard says the behaviour of a program is undefined if it adds declarations or definitions to namespace `std`, unless otherwise specified. The permission it does give is narrow: specializing a standard **class** template such as `std::hash` for a program-defined type. A `swap` for your type belongs next to the type. ## C++20: std::ranges::swap `std::ranges::swap` is a **customization point object**: a constant object, not a function template, whose call operator does the dispatch. For arguments `E1` and `E2`, the draft specifies, in order: 1. If either has class or enumeration type and an unqualified `swap(E1, E2)` is valid, call it, with overload resolution in a context that contains a deleted `template<class T> void swap(T&, T&)` and no declaration of `ranges::swap`. The deleted template keeps the unconstrained `std::swap` out: a program-defined `swap` found by ADL is selected when it beats that deleted template in overload resolution, as a non-template or a more specialized template does. 2. Otherwise, for lvalue arrays of equal extent, swap element by element. 3. Otherwise, if both are lvalues of the same type that is move constructible and assignable, exchange the values with moves. The draft adds that if the `swap` selected in step 1 does not actually exchange the values, the program is ill-formed, no diagnostic required. Because `std::ranges::swap` is an object, writing it qualified is the intended use: one name, no using-declaration, and the type's own `swap` still wins. C++20 code can write `std::ranges::swap(a, b)`; code that must build as C++17 keeps the two-step. ```cpp template <class T> void reorder(T& a, T& b) { using std::swap; swap(a, b); // C++11 onwards: finds geo::swap via ADL } // C++20 onwards, equivalent in effect: // std::ranges::swap(a, b); ``` ## Interview checklist - Qualified `std::swap` skips ADL and therefore skips the type's own `swap`. - The two-step is the standard's own evaluation context for swappable types. - Custom `swap` goes in the type's namespace or is a hidden friend, never in `std`. - `std::ranges::swap` in C++20 packages the same lookup into a single qualified call.
- Why is it undefined behaviour to add swap(geo::Polygon&, geo::Polygon&) to namespace std?The standard says a program that adds declarations or definitions to namespace std has undefined behaviour unless a rule permits it. The permission it grants is to specialize standard class templates, such as std::hash, for program-defined types. A new swap overload is a new declaration, so it belongs in the type's own namespace, where ADL finds it.
- Should a custom swap be noexcept, and why does it matter?Yes, when it only exchanges pointers or handles. Copy-and-swap assignment and other code that offers the strong exception guarantee rely on a swap that cannot throw, and std::is_nothrow_swappable reports it. A swap that exchanges buffers instead of moving elements is both cheaper and naturally non-throwing.
- std::swap(a, b) automatically uses a swap declared in the type's namespace
- The fix is to add a swap overload to namespace std
- An unqualified swap(a, b) without using std::swap works for int
- std::ranges::swap is just a new name for the same generic std::swap
- The using-declaration makes std::swap win over the type's own swap
Assumes C++20 or later for std::ranges::swap; the using std::swap; swap(a, b); idiom works the same in C++11 and C++17.