- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- copy-constructor
- copy-constructor
- destructor
- 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.