Skip to content

C++ Idiom: Copy-and-Swap

Adapted from this stackoverflow article

Copy-and-swap idiom is a elegant solution that performs assignment while avoiding code duplication and strong exception guarantee. Conceptually, it utilizes the object’s copy-constructor to create a local copy of itself, performs assignment to the other object through a swap method and then destroys the other object’s old data when the swapped local copy’s destructor.

Through the rule of three, the highlighted components (in bold) should all be present anyway except the swap method. The swap method must be non-throwing function. Notice that std::swap does not qualify as it uses the copy-constructor and assignment operator in its implementation (and we are trying to implement the assignment operator).

From this point, see the stackoverflow article for an example

Posted in C/C++, idioms. Tagged with , .