名前空間
変種
操作

std::exchange

提供: cppreference.com
< cpp‎ | utility
2018年9月5日 (水) 06:40時点におけるMilkpot (トーク | 投稿記録)による版

 
 
ユーティリティライブラリ
汎用ユーティリティ
日付と時間
関数オブジェクト
書式化ライブラリ (C++20)
(C++11)
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)
スワップと型操作
exchange
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
一般的な語彙の型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等文字列変換
(C++17)
(C++17)
 
ヘッダ <utility> で定義
template< class T, class U = T >
T exchange( T& obj, U&& new_value );
(C++14以上)
(C++20未満)
template< class T, class U = T >
constexpr T exchange( T& obj, U&& new_value );
(C++20以上)

obj の値を new_value の値で置き換え、 obj の古い値を返します。

目次

引数

obj - 値を置き換えるオブジェクト
new_value - obj に代入する値
型の要件
-
TMoveConstructible の要件を満たさなければなりません。 また、 U 型のオブジェクトから T 型のオブジェクトへのムーブ代入も可能でなければなりません

戻り値

obj の古い値。

例外

(なし)

実装例

template<class T, class U = T>
T exchange(T& obj, U&& new_value)
{
    T old_value = std::move(obj);
    obj = std::forward<U>(new_value);
    return old_value;
}

ノート

この関数はムーブ代入演算子ムーブコンストラクタを実装するときに使用することができます。

struct S
{
  int* p;
  int n;
 
  S(S&& other)
    :p{std::exchange(other.p, nullptr)}
    ,n{std::exchange(other.n, 0)}
  {}
 
  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;
  }
};

#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, static_cast<void(*)()>(f))
   std::exchange(fun,f);
   fun();
}

出力:

0
0
12
 
1, 2, 3, 4, 
 
f()

関連項目

2つのオブジェクトの値を入れ替えます
(関数テンプレート) [edit]
アトミックオブジェクトの値を非アトミック引数でアトミックに置き換え、そのアトミックの古い値を返します
(関数テンプレート) [edit]