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:

Cookie Settings

This website uses cookies to personalize content and ads, provide social media features, and analyze website traffic. In addition, information about your use of the website is shared with social media, advertising, and analytics partners. These partners may merge the information with other data that you have provided to them or that they have collected from you using the services.

For more information, please refer to our privacy policy. There you can also change your cookie settings later on.

contact icon

Contact us now