std::exchange

来自cppreference.com
< cpp‎ | utility
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
exchange
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
在标头 <utility> 定义
template< class T, class U = T >
T exchange( T& obj, U&& new_value );
(C++14 起)
(C++20 起为 constexpr)
(C++23 起条件性 noexcept)

new_value 替换 obj 的值,并返回 obj 的旧值。

参数

obj - 要替换值的对象
new_value - 要赋给 obj 的值
类型要求
-
T 必须满足可移动构造 (MoveConstructible) 。而且必须能移动赋值 U 类型对象给 T 类型对象

返回值

obj 的旧值。

异常

(无)

(C++23 前)
noexcept 说明:  
(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 不会改变)
        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_; }
 
    /// 以 newf 替换 flags_ 并返回旧值。
    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\n斐波那契数列: ";
    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()
 
斐波那契数列: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

参阅

交换两个对象的值
(函数模板)
原子地以非原子实参的值替换原子对象的值,并返回该原子对象的旧值
(函数模板)