Swap – from Simple to Subtle
We begin our exploration of basic C++ idioms with a very simple, even humble, operation—swap. The notion of swap refers to two objects exchanging places—after the swap, the first object keeps its name, but otherwise looks like the second object used to, and vice versa. This operation is so fundamental to C++ classes that the standard provides a template, std::swap
, to do just that. Rest assured that C++ manages to turn even something as basic as a swap into a complex issue with subtle nuances.
The following topics are covered in this chapter:
- How is
swap
used by the standard C++ library? - What are the applications of swap?
- How can we write exception-safe code using swap?
- How can we implement swap for our own types correctly?
- How can we correctly swap variables of an arbitrary type?