Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::exchange: replace a value and return the old one

std::exchange moves an object’s current value into the result, assigns a new value to the object, and returns the saved old state.

Version: C++23

Syntax

template<class T, class U = T>
constexpr T exchange(T& obj, U&& new_value)
    noexcept(std::is_nothrow_move_constructible_v<T> &&
             std::is_nothrow_assignable_v<T&, U>);

std::exchange(obj, new_value) from <utility> is equivalent to creating T old = std::move(obj), performing obj = std::forward<U>(new_value), and returning old. T must be move-constructible and T& assignable from U; the template is constexpr and conditionally noexcept.

It is useful for explicit state transitions, move implementations, and replacing while retrieving the previous value. The example replaces the string idle with running; the call result is a separate string containing idle.

This is not an atomic operation or a synchronization mechanism. If construction of the old value succeeds but assignment of the new one throws, obj has already been moved from and the function does not roll back. Aliasing new_value with obj, especially as std::move(obj), can create surprising self-assignment.

Examples

#include <iostream>
#include <string>
#include <utility>

int main() {
    std::string state = "idle";
    const std::string old = std::exchange(state, "running");
    std::cout << old << ' ' << state << '\n';
}

Result

idle running

std::exchange → idle running

Sources