Why do we need the copy and swap idiom in C++ ? But let me ask a question what is copy and swap idiom in c++ ?  Let us take an example to understand.

  • Let us save the code sample.cpp and try to compile and run.

  • The above program is a buggy program without proper assignment operator and copy constructor. If we run the program it will be undefined behavior.
  • The statement rec = rec_1 , will invoke default overloaded assignment operator ,and The default assignment operator in C++ recursively applies the assignment operators of the class’s members.
  • Here employee_record class containing a pointer to char array name and integer id.
  • We can consider employee_record class as a user defined data type.
  • To make the behavior  of employee_record class as a built in data type we have to provide copy constructor and overloaded assignment operator. 

So it is clearly that The compiler generated copy constructor and assignment operator may not be sufficient when we have pointers in a class. So let us modify the program as below

Why do we need the copy and swap idiom in C++?

Let us think what we have done until now…

We have made copy constructor and overloaded assignment operator. Let us look at the code ..


  • In assignment operator and copy constructor , there is code duplication. Our assignment operator effectively duplicates all the code we’ve already written  in copy constructor.
  • In overloaded assignment operator , if memory allocation of char*name would fail , then there is invalid state of object. we have to handle exception if new fails.

Copy and swap idiom is a way of solving above two problems.

  • In the above example, the parameter to the ‘operator=()’ is passed by value
  • The passing parameter by value calls copy constructor to create a employee_record object local to the ‘operator=()’ function.
  • The value of the local object is swapped with ‘*this’ object.



Related Contents to follow