std::exchange in C++

In this tutorial, you would understand what is std::exchange and how is it used in C++.

The purpose of std::exchange is that it returns the old value of the particular variable and exchanges the value of that old variable with the argument provided, unlike swap, where the values are interchanged between the variables.

What is std::exchange

std::exchange is a general-purpose function used in C++ under the header <utility>. It consists of two parameters, namely:

obj – object whose value must be replaced
new_val – the new value to assign to obj

The returned value will be the old value of obj.

For example:

int z = std::exchange(obj, new_val);

After this line of code executes,

  • obj is assigned with the value of new_val.
  • z is assigned with the value obj had.

Difference between std::exchange and std::swap

  1. swap(x,y) and exchange(x,y) are not the same. swap(x,y) would assign value of x to y and the value of y to x. But, exchange(x,y) would only assign the value of x to y and value of y remains untouched.
  2.  Only if the declaration is y=exchange(x,y) that the value of y is assigned with that of x.

Code to differentiate between exchange and swap

int main()
int x=2;
int y=4;

auto z = std::exchange(x,y);
auto y = std::exchange(x,std::string("Hello"));

int i=3;
int j=5;

return 0;

Output explanation:

  • For std::exchange, when we exchange between two integers, x will get the value of y (new value of x=4) and  z would store the value 2.
  • In the very next statement, we try to exchange between an integer and a string. Then it will do an exact forwarding of the second parameter (string “Hello” here) and move it out of the stack for you.
  • For std::swap, when we exchange between two integers, i and j, i will get the value of j and j will get the value of i (i=5, j=3). This is different from exchange as both variables are getting changed.
  • In the next statement, we are trying to swap between an int and a string. This requires both sides to be able to convert to a non constant reference. In our statement, it won’t work as there is no way to convert them into a non constant reference. However, the same worked in our exchange statement.


From the explanation, it is clear that in std::exchange, the parameter to the right, as efficient as possible, is moved into x, and the value of x is moved to the variable assigned to exchange statement.

Leave a Reply

Your email address will not be published.