Skip to content

std::exchange (C++14)

In a Nutshell

Assigns a new value to a variable while retrieving its old value, avoiding the need for manual temporary variables.

#include <utility>

Core API Quick Reference

OperationSignatureDescription
Replace and return 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

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

int main() {
    int a = 10, b = 20;
    // 交换 a 和 b,无需临时变量
    a = std::exchange(b, a);
    std::cout << a << " " << b << "\n"; // 输出: 10 10

    // 打印斐波那契数列前几项
    for (int x{0}, y{1}; x < 50; x = std::exchange(y, x + y))
        std::cout << x << " ";
}

Embedded Applicability: Medium

  • It is a pure inline function with no additional heap allocation or system call overhead.
  • It relies on move semantics; when using it with custom types, verify the actual cost of move construction/assignment.
  • It is very concise for implementing move constructors and state machine transitions, making it suitable for resource-rich environments.
  • Supported as constexpr since C++20, allowing for compile-time usage.

Compiler Support

GCCClangMSVC
5.03.419.0

See Also


Part of the content references cppreference.com, licensed under CC-BY-SA 4.0

v0.7.0-9-g940ec1b · 940ec1b · 2026-07-05