Copy-and-Swap Idiom

Learn about the copy-and-swap idiom with safe and unsafe variants.

Before moving on to discuss the copy-and-swap idiom, let’s discuss the exception safety, which is important to understand the copy-and-swap idiom.

Exception safety

An operation can be considered exception-safe if those operations leave the object in a valid state. In short, the exception should not corrupt the program or leak resources. This means that all objects allocated using malloc or new are destroyed at the end, and all the resources are closed (RAII).

Note: David Abrahams is an author and computer programmer. He is well recognized for his contributions to the C++ programming language. His contributions to the language include the development of an exception theory and participation on the C++ standards committee.

Abrahams’s guarantees

Exception safety is provided on multiple levels in the C++ standard library:

  • No-throw guarantee: As its name suggests, operations are always successful, and functions never throw exceptions at this level. All the expected errors are concealed or reported internally instead of displayed to the user.

  • Strong exception safety: The operation will be either successful or will show the exception, but even in the case of an exception, it will not leak memory, and the program’s state will not be modified. The program’s state is rolled back to the previous state before the function call that caused the exception.

  • Basic exception safety: The exception safety at this level can cause operation failure, but all the basic invariants are maintained. Resources aren’t leaked, and it’s ensured that failed operations don’t render any side effects.

  • No exception safety: No guarantees are made for successful operations. The function can throw an error and can be in an invalid state. It results in resource leaks and might not be able to maintain invariants.

Copy-and-swap idiom

Any class that manages resources (allocates dynamic array) needs to implement the following:

  • Constructor
  • Copy assignment operator overloading
  • Destructor

While this will ensure basic exception safety (no memory leakage), it still won’t ensure strong exception safety. Let’s have a look at the copy assignment operator’s code.

Get hands-on with 1200+ tech skills courses.