Search code examples
c++performanceoptimizationstlc++-faq

How to overload std::swap()


std::swap() is used by many std containers (such as std::list and std::vector) during sorting and even assignment.

But the std implementation of swap() is very generalized and rather inefficient for custom types.

Thus efficiency can be gained by overloading std::swap() with a custom type specific implementation. But how can you implement it so it will be used by the std containers?


Solution

  • The right way to overload std::swap's implemention (aka specializing it), is to write it in the same namespace as what you're swapping, so that it can be found via argument-dependent lookup (ADL). One particularly easy thing to do is:

    class X
    {
        // ...
        friend void swap(X& a, X& b)
        {
            using std::swap; // bring in swap for built-in types
    
            swap(a.base1, b.base1);
            swap(a.base2, b.base2);
            // ...
            swap(a.member1, b.member1);
            swap(a.member2, b.member2);
            // ...
        }
    };