std::exchange

来自cppreference.com
< cpp‎ | utility
 
 
 
在标头 <utility> 定义
template<class T, class U = T >
T exchange( T& obj, U&& new_value );
(C++14 起)
(C++20 起为 constexpr)
(C++23 起条件性 noexcept)

new_value 替换 obj 的值,并返回 obj 的旧值。

目录

[编辑]参数

obj - 要替换值的对象
new_value - 要赋给 obj 的值
类型要求
-
T 必须满足可移动构造(MoveConstructible) 。而且必须能移动赋值 U 类型对象给 T 类型对象

[编辑]返回值

obj 的旧值。

[编辑]异常

(无)

(C++23 前)
noexcept 说明:  
(C++23 起)

[编辑]可能的实现

template<class T, class U = T>constexpr// C++20 起 T exchange(T& obj, U&& new_value)noexcept(// 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 可以在实现移动赋值运算符移动构造函数时使用: 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);// 移动 n,并于 other.n 留下零// 注意:自我移动赋值时,n 不会改变// 令注意:若 n 是需要特殊清理的不透明资源句柄,则此资源会泄漏return*this;}};
功能特性测试标准功能特性
__cpp_lib_exchange_function201304L(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_;}   /// 以 newf 替换 flags_ 并返回旧值。 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;   // 因为第二模板形参有默认值,故能以花括号初始化式列表为第二实参。// 下方表达式等价于 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)();   // 模板形参的默认值亦使得能以通常函数为第二实参。// 下方表达式等价于 std::exchange(fun, static_cast<void(*)()>(f)) std::exchange(fun, f); fun();   std::cout<<"\n\n斐波那契数列: ";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()   斐波那契数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

[编辑]参阅

交换两个对象的值
(函数模板)[编辑]
原子地以非原子实参的值替换原子对象的值,并返回该原子对象的旧值
(函数模板)[编辑]
close