![]() |
VOOZH | about |
In C++, providing a swap function for the class allows efficient swapping of the objects of that class type which can be important for many algorithms like sorting algorithms or container manipulations. In this article, we will learn how to implement a swap function for our own user defined class.
There are two ways in which we can provide swap function for our class.
The second method is better as it provides a concise and efficient method of swapping in most of the cases.
To provide the swap function for your class using std::swap, follow the below steps:
- Define the swap function inside your class.
- Provide a non-member swap function that calls the member swap function.
- Optionally, provide a specialized std::swap function template for your class.
Swap Function?By default, the STL uses std::swap to exchange the values of two objects. While std::swap works well for many cases, it may not be the most efficient for your custom class. Implementing a custom swap function allows you to control how member variables are exchanged, potentially improving performance by avoiding unnecessary copying or allocation operations.
Here’s how you can implement a swap function for the custom class:
Before swap: data1: 1, data2: 1.1 data1: 2, data2: 2.2 After swap: data1: 2, data2: 2.2 data1: 1, data2: 1.1