What std::exchange does, and how to remember it--Jonathan Boccara

If you had troubles.

What std::exchange does, and how to remember it

by Jonathan Boccara

From the article:

std::exchange was introduced in the C++ standard library in C++14 under the header <utility>.

Its name suggests that it’s a general-purpose and useful function, and its template prototype working with any type confirms this impression.

I don’t know about you, but I always had a problem with std::exchange: I couldn’t remember what it was doing. I learnt several times the operations that std::exchange performs, but each time I forgot them soon after.

Then at some point it clicked: std::exchange is a setter returning the old value. Ignoring the name “exchange” but thinking of it as a “setter” helped me make it stick to my mind.

It might just be me having a hard time with std::exchange for some reason. But just in case you also have issues remembering the operations of std::exchange, let’s see why std::exchange has this meaning, and why this meaning is not obvious from its name.

This should help you remember it once and for all...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.