std::exchange
来自 cppreference.cn
定义于头文件 <utility> |
||
template< class T, class U = T > T exchange( T& obj, U&& new_value ); |
(自 C++14 起) (constexpr 自 C++20 起) (conditionally noexcept 自 C++23 起) |
|
用 new_value 替换 obj 的值,并返回 obj 的旧值。
目录 |
[编辑] 参数
obj | - | 要替换其值的对象 |
new_value | - | 要赋值给 obj 的值 |
类型要求 | ||
-T 必须满足 MoveConstructible 的要求。此外,必须可以将 U 类型的对象移动赋值给 T 类型的对象。 |
[编辑] 返回值
obj 的旧值。
[编辑] 异常
(无) |
(直到 C++23) |
noexcept 规范:
noexcept( std::is_nothrow_move_constructible_v<T> && |
(自 C++23 起) |
[编辑] 可能的实现
template<class T, class U = T> constexpr // Since C++20 T exchange(T& obj, U&& new_value) noexcept( // Since C++23 std::is_nothrow_move_constructible<T>::value && std::is_nothrow_assignable<T&, U>::value ) { T old_value = std::move(obj); obj = std::forward<U>(new_value); return old_value; } |
[编辑] 注解
当实现移动构造函数时,以及对于不需要特殊清理的成员,移动赋值运算符,可以使用 std::exchange
struct S { int n; S(S&& other) noexcept : n{std::exchange(other.n, 0)} {} S& operator=(S&& other) noexcept { n = std::exchange(other.n, 0); // Move n, while leaving zero in other.n // Note: in case of self-move-assignment, n is unchanged // Also note: if n is an opaque resource handle that requires // special cleanup, the resource is leaked. return *this; } };
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_exchange_function |
201304L |
(C++14) | std::exchange
|
[编辑] 示例
运行此代码
#include <iostream> #include <iterator> #include <utility> #include <vector> class stream { public: using flags_type = int; public: flags_type flags() const { return flags_; } // Replaces flags_ by newf, and returns the old value. flags_type flags(flags_type newf) { return std::exchange(flags_, newf); } private: flags_type flags_ = 0; }; void f() { std::cout << "f()"; } int main() { stream s; std::cout << s.flags() << '\n'; std::cout << s.flags(12) << '\n'; std::cout << s.flags() << "\n\n"; std::vector<int> v; // Since the second template parameter has a default value, it is possible // to use a braced-init-list as second argument. The expression below // is equivalent to std::exchange(v, std::vector<int>{1, 2, 3, 4}); std::exchange(v, {1, 2, 3, 4}); std::copy(begin(v), end(v), std::ostream_iterator<int>(std::cout, ", ")); std::cout << "\n\n"; void (*fun)(); // The default value of template parameter also makes possible to use a // normal function as second argument. The expression below is equivalent to // std::exchange(fun, static_cast<void(*)()>(f)) std::exchange(fun, f); fun(); std::cout << "\n\nFibonacci sequence: "; for (int a{0}, b{1}; a < 100; a = std::exchange(b, a + b)) std::cout << a << ", "; std::cout << "...\n"; }
输出
0 0 12 1, 2, 3, 4, f() Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
[编辑] 参见
交换两个对象的值 (函数模板) | |
(C++11)(C++11) |
原子地用非原子参数替换原子对象的值,并返回原子的旧值 (函数模板) |