名稱空間
變體
操作

std::exchange

來自 cppreference.com
< cpp‎ | 工具
 
 
 
在標頭檔案 <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)
noexcept 規範:  
(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;
    }
};
特性測試 標準 特性
__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, ...

[編輯] 參閱

交換兩個物件的值
(函式模板) [編輯]
原子地將原子物件的值替換為非原子引數,並返回原子的舊值
(函式模板) [編輯]