std::exchange

From cppreference.com
< cpp‎ | utility
Defined in header <utility>
template< class T, class U = T >
T exchange( T& obj, U&& new_value );
(since C++14)

Replaces the value of obj with new_value and returns the old value of obj.

Parameters

obj - object whose value to replace
new_value - the value to assign to obj
Type requirements
-
T must meet the requirements of MoveConstructible. Also, it must be possible to move-assign objects of type U to objects of type T

Return value

The old value of obj

Exceptions

(none)

Possible implementation

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;
}

Notes

This function can be used when implementing move assignment operators:

struct S
{
  int* p;
  int n;
  S& operator=(S&& other) {
    p = std::exchange(other.p, nullptr); // move p, while leaving nullptr in other.p
    n = std::exchange(other.n, 0); // move n, while leaving zero in other.n
    return *this;
  }
}