Namespaces
Variants

std:: exchange

From cppreference.net
Utilities library
定义于头文件 <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 可在实现 移动构造函数 时使用,对于不需要 特殊清理 的成员,也可用于实现 移动赋值运算符

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;
    // 由于第二个模板参数具有默认值,可以使用花括号初始化列表作为第二个参数。
    // 下面的表达式等价于 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\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, ...

参见

交换两个对象的值
(函数模板)
以原子操作方式用非原子参数替换原子对象的值,并返回该原子对象的旧值
(函数模板)