During some c++ practicing, I was trying to learn and adopt the copy-swap idiom following this thoroughfully explanation on this question: the Copy-Swap Idiom.
But I found some code I had never seen: using std::swap; // allow ADL
in this example
class dumb_array
{
public:
// ...
void swap(dumb_array& pOther) // nothrow
{
using std::swap; // allow ADL /* <===== THE LINE I DONT UNDERSTAND */
swap(mSize, pOther.mSize); // with the internal members swapped,
swap(mArray, pOther.mArray); // *this and pOther are effectively swapped
}
};
- what does
using std::swap;
mean inside the body of a function implementation ? - what does ADL mean ?
This mechanism is normally used in templated code, i.e.
template <typename Value> class Foo
.Now the question is which swap to use.
std::swap<Value>
will work, but it might not be ideal. There's a good chance that there's a better overload ofswap
for typeValue
, but in which namespace would that be? It's almost certainly not instd::
(since that's illegal), but quite likely in the namespace ofValue
. Likely, but far from certain.In that case,
swap(myValue, anotherValue)
will get you the "best" swap possible. Argument Dependent Lookup will find any swap in the namespace whereValue
came from. Otherwise theusing
directive kicks in, andstd::swap<Value>
will be instantiated and used.In your code,
mSize
is likely an integral type, andmArray
a pointer. Neither has an associated namespace, andstd::swap
is with 99.9% certainty optimal for them anyway. Therefore, theusing std::swap;
declaration seems useless here.The
using
keyword has scoped effect.This means that
std::swap
can be referred to asswap
during the scope of theusing
keyword.Short answer
needed to avoid recursive call to the member swap. Member swap disables ADL.