正常
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.
Header
#include <utility>
Core API Quick Reference
| Operation | Signature | Description |
|---|---|---|
| Replace and return old value | template<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
constexprsince C++20, allowing for compile-time usage.
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 5.0 | 3.4 | 19.0 |
See Also
Part of the content references cppreference.com, licensed under CC-BY-SA 4.0