What is the copy-and-swap idiom in C++?

The assignment consists of 2 steps, tearing an object's old state and building a new state for it. The destructor is used for the first step and a copy constructor does the second step. Implementing both of these is straightforward. But when overloading the assignment operator, it can become quite difficult to implement. The copy and swap idiom is a solution for the same.

This idiom uses the copy-constructor to build a local copy of the data. It then swaps the old data with the new data using the swap function. The temporary copy is then destructed using the destructor. We finally have only a copy of the new data.

So, the copy-and-swap idiom needs three things − a copy-constructor, a destructor, and a swap function. A swap function is a non-throwing function that swaps two objects of a class, the member. Note − You mustn't use the std:: swap function as it internally uses copy constructor and assignment operator to achieve the same.

Updated on: 23-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started