Skip to content

std::exchange (C++14) ​

In a Nutshell ​

Assigns a new value to a variable and hands you its old value at the same time, sparing you a hand-written temporary.

#include <utility>

Core API Quick Reference ​

OperationSignatureDescription
Replace and return the old valuetemplate<class T, class U = T> T exchange(T& obj, U&& new_value);Replaces obj with new_value and returns the old value of obj

Minimal Example ​

C++
// Standard: C++14
#include <iostream>
#include <utility>

int main() {
    int a = 10, b = 20;
    // Swap a and b without a temporary variable
    a = std::exchange(b, a);
    std::cout << a << " " << b << "\n"; // Output: 20 10

    // Print the first few Fibonacci numbers
    for (int x{0}, y{1}; x < 50; x = std::exchange(y, x + y))
        std::cout << x << " ";
}

Embedded Applicability: Medium ​

  • A pure inline function, with no extra heap allocation or system-call overhead
  • Relies on move semantics; when using it with custom types, verify the actual cost of the move constructor/assignment
  • Very concise for implementing move constructors and state machine transitions, a good fit for resource-rich targets
  • constexpr since C++20, so it can be used at compile time

Compiler Support ​

GCCClangMSVC
5.03.419.0

See Also ​


Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0

pdf-latest-4-g85128cc · 85128cc · 2026-10-05