4

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

Get Hands-On Design Patterns with C++ - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.