Toilet Paper 62

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:

ToiletPaper #62: Copy- und Swap-Idiom: Bild 1

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

ToiletPaper #62: Copy- und Swap-Idiom: Bild 2

.

Further aspects

  • C++ 11 – Move constructor and move assignment operator (rule of five)

---

Author

Marian Wieczorek / Software Architect / Business Division Automotive Bavaria

That also might be interesting for you:

Wir verwenden Cookies, um unsere Webseite für Sie zu optimieren. Mit dem Besuch unserer Webseite erklären Sie sich damit einverstanden. // Our website is using cookies to improve your experience. By continuing to browse the site, you are agreeing to our use of cookies.

Weitere Informationen finden Sie in unserer Datenschutzerklärung. // For more information, please refer to our privacy policy.