VOOZH about

URL: https://www.geeksforgeeks.org/cpp/overload-swap-function-cpp/

⇱ How to Overload std::swap()? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Overload std::swap()?

Last Updated : 23 Jul, 2025

In C++, std::swap is a standard library function that is used to exchange the values of two objects. There might be situations where we want to provide a custom implementation for our user-defined types to improve performance or handle special cases for such cases we need to overload std::swap. In this article, we will learn how to overload std::swap for custom types to ensure that our implementation integrates seamlessly with the standard library.

Need for Custom swap() Function in C++

By default, the STL uses std::swap to exchange the values of two objects. While std::swap works well in many cases, it may not be the most efficient for our custom class. Implementing a custom swap function allows us to control how member variables are exchanged, also improving performance by avoiding unnecessary copying or allocation operations.

Overloading std::swap for a User-Defined Class

The default, swaps objects by copying them, which can be slow if the objects are large or manage resources. std::swap for a user-defined class allows us to define a faster, more efficient way to swap our objects.

Steps to Overload std::swap()

To overload std::swap for your class, follow these three steps:

  1. First, define a swap function inside your class for implementing the logic for swapping the internal state of two objects within the class.
  2. Then, provide a non-member swap Function that will call the member swap function.
  3. Optionally, specialize std::swap for your class to ensure that your class’s swap function is used by the standard library.

C++ Program to Overload std::swap Function

The below example demonstrates how we can implement std::swap for a custom class.


Output
Before swap:
data1: 1, data2: 1.1
data1: 2, data2: 2.2
After swap:
data1: 2, data2: 2.2
data1: 1, data2: 1.1

Benefits of Overloading std::swap

  • Swapping objects using swap is often more efficient than copying objects.
  • Many standard library algorithms rely on efficient swapping, such as sorting algorithms and containers like std::vector and std::map.
  • Overloading swap can facilitate exception-safe code by enabling the copy-and-swap idiom.
Comment
Article Tags: