How to overload std::swap()

Adam picture Adam · Aug 14, 2008 · Viewed 31.6k times · Source

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?

Answer

Dave Abrahams picture Dave Abrahams · Apr 21, 2010

The right way to overload swap 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);
        // ...
    }
};