How To Use std::exchange In C++

C++ is a very precise programming language that allows you to use memory operations in a wide variety of ways. Mastering efficient memory handling will improve your app performance at run time and can result in faster applications that have optimal memory usage. One of the many useful features that come with the C++14 standard is the std::exchange algorithm that is defined in the utility header. In this post, we explain how to use std::exchange in C++.

What is std::exchange in C++?

The std::exchange algorithm is defined in the header and it is a built-in function that comes with C++14. The std::exchange algorithm copies the new value to a given object and it will return the old value of that object.

Here is the template definition syntax (since C++14, until C++20):

How to use std::exchange in C++?

We can use std::exchange to exchange variables values as below, and we can obtain old value from the return value of std::exchange.

After these lines, x is now 333 and y is the old value of x , 500.

We can use std::exchange to set values of object lists (i.e vectors) as shown below:

In addition, we can copy old values to another object list as we show in the following example:

We can use std::exchange to change function definitions too, for example assume we have myf1() function, now we want to exchange myf() function to myf1() function, this is how we can do:

Is there a full example of how to use std::exchange in C++?

Here is a full example of how to use std::exchange in C++.

and the output will be as follows,

For more information about this std::exchange feature, please see https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3668.html

Note that, this function is being improved in C++23 standards.

How To Use stdexchange In C++ the C++ Builder Logo

C++ Builder is the easiest and fastest C and C++ IDE for building simple or professional applications on the Windows, MacOS, iOS & Android operating systems. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs.

There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here