
Copy and Swap Idiom
Problem
You are about to write a C++ class that needs a custom destructor, copy constructor, and assignment operator (rule of three). You worry about code duplication, correctness, and exception safety.
Solution
The copy and swap idiom uses the copy constructor and a swap function in order to implement the assignment operator safely. A drawback is that assignment requires a copy now. However, keep in mind to optimize late!
Example
A counter-example that duplicates code, must avoid self-assignment, and is not exception-safe:

The swap function, copy constructor, and assignment operator of the copy and swap idiom:

.
Further aspects
- C++ 11 – Move constructor and move assignment operator (rule of five)
---
Author
Marian Wieczorek / Software Architect / Business Division Automotive Bavaria
Click here for the Toilet Paper #62: Copy- und Swap-Idiom (pdf)
That also might be interesting for you:
ToiletPaper #53: Order of evaluation in C, Objective C and C++ (pdf)