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.
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!
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:
- C++ 11 – Move constructor and move assignment operator (rule of five)
Marian Wieczorek / Software Architect / Business Division Automotive Bavaria
That also might be interesting for you: