Typically, prefer the specialized
a.swap(b) over the more generic
std::swap(a, b) when the former exists.
This is good enough advice for most cases, but there's more to the story.
Typically, when the former exists, there is also a namespace-scope overload of
swap visible via
argument-dependent lookup. For ADL to occur, the function name must be an
unqualified-id, i.e.,
std:: must not appear on the left, as in
/*std::*/swap(a, b)
And this will typically do the right thing.
In generic code, the invocation
1 2
|
using std::swap;
swap(a, b);
| |
Is sometimes used so that ADL has an opportunity to find custom swap overloads, and if that fails, generic
std::swap is available as a fall-back.
ADL can cause very surprising behavior, even for experts. It is a secondary reason I suggest that students avoid
using namespace.