128

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?

1

4 Answers 4

154

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);
        // ...
    }
};
17
  • 12
    In C++2003 it's at best underspecified. Most implementations do use ADL to find swap, but no it's not mandated, so you can't count on it. You can specialize std::swap for a specific concrete type as shown by the OP; just don't expect that specialization to get used, e.g. for derived classes of that type. Jun 1, 2010 at 15:52
  • 18
    I would be surprised to find that implementations still don't use ADL to find the correct swap. This is an old issue on the committee. If your implementation doesn't use ADL to find swap, file a bug report. Feb 23, 2011 at 1:32
  • 5
    @Mozza314: It depends. A std::sort that uses ADL to swap elements is non-conforming C++03 but conforming C++11. Also, why -1 an answer based on the fact that clients might use non-idiomatic code?
    – JoeG
    Dec 8, 2011 at 13:10
  • 5
    @curiousguy: If reading the standard was just a simple matter of reading the standard, you’d be right :-). Unfortunately, the intent of the authors matters. So if the original intent was that ADL could or should be used, it’s underspecified. If not, then it’s just a plain old breaking change for C++0x, which is why I wrote “at best” underspecified. Jul 24, 2013 at 23:09
  • 5
    @curiousguy Yes, he does have a source! He is Dave Abrahams
    – Paolo M
    Nov 11, 2015 at 10:53
81

Attention Mozza314

Here is a simulation of the effects of a generic std::algorithm calling std::swap, and having the user provide their swap in namespace std. As this is an experiment, this simulation uses namespace exp instead of namespace std.

// simulate <algorithm>

#include <cstdio>

namespace exp
{

    template <class T>
    void
    swap(T& x, T& y)
    {
        printf("generic exp::swap\n");
        T tmp = x;
        x = y;
        y = tmp;
    }

    template <class T>
    void algorithm(T* begin, T* end)
    {
        if (end-begin >= 2)
            exp::swap(begin[0], begin[1]);
    }

}

// simulate user code which includes <algorithm>

struct A
{
};

namespace exp
{
    void swap(A&, A&)
    {
        printf("exp::swap(A, A)\n");
    }

}

// exercise simulation

int main()
{
    A a[2];
    exp::algorithm(a, a+2);
}

For me this prints out:

generic exp::swap

If your compiler prints out something different then it is not correctly implementing "two-phase lookup" for templates.

If your compiler is conforming (to any of C++98/03/11), then it will give the same output I show. And in that case exactly what you fear will happen, does happen. And putting your swap into namespace std (exp) did not stop it from happening.

Dave and I are both committee members and have been working this area of the standard for a decade (and not always in agreement with each other). But this issue has been settled for a long time, and we both agree on how it has been settled. Disregard Dave's expert opinion/answer in this area at your own peril.

This issue came to light after C++98 was published. Starting about 2001 Dave and I began to work this area. And this is the modern solution:

// simulate <algorithm>

#include <cstdio>

namespace exp
{

    template <class T>
    void
    swap(T& x, T& y)
    {
        printf("generic exp::swap\n");
        T tmp = x;
        x = y;
        y = tmp;
    }

    template <class T>
    void algorithm(T* begin, T* end)
    {
        if (end-begin >= 2)
            swap(begin[0], begin[1]);
    }

}

// simulate user code which includes <algorithm>

struct A
{
};

void swap(A&, A&)
{
    printf("swap(A, A)\n");
}

// exercise simulation

int main()
{
    A a[2];
    exp::algorithm(a, a+2);
}

Output is:

swap(A, A)

Update

An observation has been made that:

namespace exp
{    
    template <>
    void swap(A&, A&)
    {
        printf("exp::swap(A, A)\n");
    }

}

works! So why not use that?

Consider the case that your A is a class template:

// simulate user code which includes <algorithm>

template <class T>
struct A
{
};

namespace exp
{

    template <class T>
    void swap(A<T>&, A<T>&)
    {
        printf("exp::swap(A, A)\n");
    }

}

// exercise simulation

int main()
{
    A<int> a[2];
    exp::algorithm(a, a+2);
}

Now it doesn't work again. :-(

So you could put swap in namespace std and have it work. But you'll need to remember to put swap in A's namespace for the case when you have a template: A<T>. And since both cases will work if you put swap in A's namespace, it is just easier to remember (and to teach others) to just do it that one way.

19
  • 4
    Thankyou very much for the detailed answer. I am clearly less knowledgeable about this and was actually wondering how overloading and specialisation could produce different behaviour. However, I'm not suggesting overloading but specialisation. When I put template <> in your first example I get output exp::swap(A, A) from gcc. So, why not prefer specialisation?
    – voltrevo
    Dec 9, 2011 at 0:26
  • 3
    in-class friend syntax should be fine. I would try to limit using std::swap to function scope within your headers. Yes, swap is almost a keyword. But no, it is not quite a keyword. So best not to export it to all namespaces until you really have to. swap is much like operator==. The biggest difference is that no ever even thinks of calling operator== with qualified namespace syntax (it would just be too ugly). Dec 9, 2011 at 1:17
  • 16
    @NielKirk: What you are seeing as complication is simply too many wrong answers. There is nothing complicated about Dave Abrahams' correct answer: "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)." Oct 2, 2013 at 14:23
  • 3
    @codeshot: Sorry. Herb has been trying to get this message across since 1998: gotw.ca/publications/mill02.htm He doesn't mention swap in this article. But this is just another application of Herb's Interface Principle. Aug 22, 2015 at 21:20
  • 2
    Visual Studio does not yet correctly implement the 2-phase lookup rules introduced in C++98. That means that in this example VS calls the wrong swap. This adds a new wrinkle I hadn't previously considered: In the case of template<class T> struct A, putting your swap into namespace std renders your code non-portable. Try your example out on wandbox to see how gcc and clang handle it. May 5, 2018 at 15:59
55

You're not allowed (by the C++ standard) to overload std::swap, however you are specifically allowed to add template specializations for your own types to the std namespace. E.g.

namespace std
{
    template<>
    void swap(my_type& lhs, my_type& rhs)
    {
       // ... blah
    }
}

then the usages in the std containers (and anywhere else) will pick your specialization instead of the general one.

Also note that providing a base class implementation of swap isn't good enough for your derived types. E.g. if you have

class Base
{
    // ... stuff ...
}
class Derived : public Base
{
    // ... stuff ...
}

namespace std
{
    template<>
    void swap(Base& lha, Base& rhs)
    {
       // ...
    }
}

this will work for Base classes, but if you try to swap two Derived objects it will use the generic version from std because the templated swap is an exact match (and it avoids the problem of only swapping the 'base' parts of your derived objects).

NOTE: I've updated this to remove the wrong bits from my last answer. D'oh! (thanks puetzk and j_random_hacker for pointing it out)

6
  • 14
    Downvoted because the correct way to customize swap is to do so in your own namespace (as Dave Abrahams points out in another answer). Feb 23, 2011 at 1:30
  • Is it forbidden to overload std::swap (or anything else), but outside of std::swap namespace?
    – Kos
    Jul 28, 2011 at 14:07
  • 16
    @HowardHinnant, Dave Abrahams: I disagree. On what basis do you claim your alternative is the "correct" way? As puetzk quoted from the standard, this is specifically allowed. While I'm new to this issue I really don't like the method you advocate because if I define Foo and swap that way someone else who uses my code is likely to use std::swap(a, b) rather than swap(a, b) on Foo, which silently uses the inefficient default version.
    – voltrevo
    Dec 8, 2011 at 12:39
  • 5
    @Mozza314: The space and formatting constraints of the comment area did not allow me to fully reply to you. Please see the answer I've added titled "Attention Mozza314". Dec 8, 2011 at 23:53
  • 1
    @HowardHinnant, am I right in thinking this technique could also easily breach the one-definition-rule? If a translation unit has included <algorithm> and a forward declaration of class Base; whilst another includes the header, above, then you have two different instances of std::swap<Base>. I recall this is forbidden in a conforming program but using this technique means you must successfully prevent users of your class from writing a forward declaration - they must be forced somehow to always include your header to achieve their goals. This turns out to be impractical to achieve at scale.
    – codeshot
    Nov 6, 2016 at 15:25
31

While it's correct that one shouldn't generally add stuff to the std:: namespace, adding template specializations for user-defined types is specifically allowed. Overloading the functions is not. This is a subtle difference :-)

17.4.3.1/1 It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces with namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library results in undefined behaviour unless the declaration depends on a user-defined name of external linkage and unless the template specialization meets the standard library requirements for the original template.

A specialization of std::swap would look like:

namespace std
{
    template<>
    void swap(myspace::mytype& a, myspace::mytype& b) { ... }
}

Without the template<> bit it would be an overload, which is undefined, rather than a specialization, which is permitted. @Wilka's suggest approach of changing the default namespace may work with user code (due to Koenig lookup preferring the namespace-less version) but it's not guaranteed to, and in fact isn't really supposed to (the STL implementation ought to use the fully-qualified std::swap).

There is a thread on comp.lang.c++.moderated with a long dicussion of the topic. Most of it is about partial specialization, though (which there's currently no good way to do).

6
  • 7
    One reason it's wrong to use function template specialization for this (or anything): it interacts in bad ways with overloads, of which there are many for swap. For example, if you specialize the regular std::swap for std::vector<mytype>&, your specialization won't get chosen over the standard's vector-specific swap, because specializations aren't considered during overload resolution. Feb 24, 2011 at 20:46
  • 4
    This is also what Meyers recommends in Effective C++ 3ed (Item 25, pp 106-112).
    – jww
    Sep 5, 2011 at 16:28
  • 2
    @DaveAbrahams: If you specialize (without explicit template arguments), partial ordering will cause it to be a specialization of the vector version and it will be used. Mar 13, 2018 at 13:54
  • 1
    @DavisHerring actually, no, when you do that partial ordering plays no role. The problem isn't that you can't call it at all; it's what happens in the presence of apparently-less-specific overloads of swap: wandbox.org/permlink/nck8BkG0WPlRtavV Mar 15, 2018 at 15:20
  • 2
    @DaveAbrahams: The partial ordering is to select the function template to specialize when the explicit specialization matches more than one. The ::swap overload you added is more specialized than the std::swap overload for vector, so it captures the call and no specialization of the latter is relevant. I’m not sure how that’s a practical problem (but neither am I claiming that this is a good idea!). Mar 15, 2018 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.