首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::exchange

Defined in header <utility>

?

?

template< class T, class U = T > T exchange( T& obj, U&& new_value );

?

(since C++14)

替换obj带着new_value的旧值obj...

参数

obj

-

object whose value to replace

new_value

-

the value to assign to obj

类型要求

-T必须符合可移动建筑的要求。此外,必须可以将U型对象移动到T型对象。

返回值

旧的价值obj...

例外

%280%29

可能的实施

模板<类T,类U=T>T交换%28 t&obj,U&New[医]值%29{T旧[医]值=std::移动%28 obj%29;obj=std::正向<U>28%新[医]值%29;返回旧[医]价值;}

*。

注记

此函数可用于实现移动分配运算符*

二次

代码语言:javascript
复制
struct S
{
  int* p;
  int n;
  S& operator=(S&& other) {
    p = std::exchange(other.p, nullptr); // move p, while leaving nullptr in other.p
    n = std::exchange(other.n, 0); // move n, while leaving zero in other.n
    return *this;
  }
}

二次

二次

代码语言:javascript
复制
#include <iostream>
#include <utility>
#include <vector>
#include <iterator>
 
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, std::static_cast<void(*)()>(f))
   std::exchange(fun,f);
   fun();
}

二次

产出:

二次

代码语言:javascript
复制
0
0
12
 
1, 2, 3, 4, 
 
f()

二次

另见

swap

swaps the values of two objects (function template)

atomic_exchangeatomic_exchange_explicit (C++11)(C++11)

atomically replaces the value of the atomic object with non-atomic argument and returns the old value of the atomic (function template)

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com