Codectionary / Developer documentation / C++

C++ std::exchange state transitions

C++14 exchange replaces a value and returns its previous value. It expresses consume-and-reset operations and is often useful in move constructors or one-shot state handling.

Syntax

auto previous = std::exchange(value, replacement);

Examples

C++ std::exchange state transitions

Save as main.cpp and compile with a C++20 compiler, for example g++ -std=c++20 main.cpp -o example. The article states the minimum language version.

#include <utility>
#include <iostream>
int main() {
    int pending = 7;
    int batch = std::exchange(pending, 0);
    std::cout << batch << ' ' << pending << '\n';
}
  1. Output: 7 0. The old pending count becomes the batch while the stored count resets.

Best practices

  • exchange is an ordinary operation, not atomic synchronization. Use atomic::exchange when coordinating shared atomic state.

Runtime & versions

Compiled native applications. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ISO C++ resources

Specifications & further reading