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';
}- 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