Namespaces
Variants

std::exchange

ja.cppreference.net より
 
 
ユーティリティライブラリ
言語サポート
型サポート (基本型、RTTI)
ライブラリ機能テストマクロ (C++20)
プログラムユーティリティ
可変引数関数
コルーチンサポート (C++20)
契約サポート (C++26)
三方比較
(C++20)
(C++20)(C++20)(C++20)    
(C++20)(C++20)(C++20)

汎用ユーティリティ
関係演算子 (C++20で非推奨)
整数比較関数
(C++20)(C++20)(C++20)    
(C++20)
Swap と 型操作
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
共通語彙型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)



 
ヘッダ <utility>
template< class T, class U = T >
T exchange( T& obj, U&& new_value );
で定義 (C++14 から)
(C++20 から constexpr)
(C++23 から条件付き noexcept)

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

パラメータ

obj - 値を置き換える対象のオブジェクト
new_value - obj に代入する値
型要件
-
T は MoveConstructible の要件を満たさなければならない。また、 U 型のオブジェクトを T 型のオブジェクトにムーブ代入可能でなければならない。

戻り値

obj の古い値。

例外

(なし)

(C++23まで)
(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 は、 move constructors および、 special cleanup を必要としないメンバーに対する move assignment operators の実装時に使用できます:

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_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_; }
    // flags_をnewfで置き換え、古い値を返す
    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;
    // 第2テンプレートパラメータにデフォルト値があるため、
    // 波括弧初期化リストを第2引数として使用可能
    // 以下の式は 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)();
    // テンプレートパラメータのデフォルト値により、通常の関数を
    // 第2引数として使用することも可能
    // 以下の式は 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, ...

関連項目

2つのオブジェクトの値を交換する
(関数テンプレート)
アトミックオブジェクトの値を非アトミック引数でアトミックに置き換え、アトミックオブジェクトの古い値を返す
(関数テンプレート)