- 参考C++标准文档
std::exchange
- 定义于: <utility>
- C++14 至 C++20前的定义:
template< class T, class U = T > T exchange( T& obj, U&& new_value );
- C++20定义:
template< class T, class U = T > constexpr T exchange( T& obj, U&& new_value );
- 使用new_value 替换 obj 的值,并返回 obj 的旧值。(右边替换左边,返回左边的初值)
- T 必须满足可移动构造 (MoveConstructible) 的要求。而且必须能移动赋值 U 类型对象给 T 类型对象
【可能的实现】
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); // 移动 p ,同时留 nullptr 于 other.p 中 n = std::exchange(other.n, 0); // 移动 n ,同时留零于 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_; } /// 以 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(); }
- 输出
0 0 12 1, 2, 3, 4, f()