How does “using std::swap” enable ADL?

Just wanted to add why this idiom is used at all, which seemed like the spirit of the original question.

This idiom is used within many std library classes where swap is implemented. From http://www.cplusplus.com/reference/algorithm/swap/:

Many components of the standard library (within std) call swap in an
unqualified manner to allow custom overloads for non-fundamental types
to be called instead of this generic version: Custom overloads of swap
declared in the same namespace as the type for which they are provided
get selected through argument-dependent lookup over this generic
version.

So the purpose of using an unqualified “swap” to swap member variables in the function you described is so that ADL can find customized swap functions for those classes (if they exist elsewhere).

Since these customized classes don’t exist within the class you’re referencing (mSize and mArray is a std::size_t and an int*, respectively, in the original example), and the std::swap works just fine, the author added a comment that this was not necessary in this case, but good practice. He would have gotten the same results had he explicitly called std::swap, as is pointed out in the previous answer.

Why is it good practice? Because if you have as members instances of classes for which custom swap is defined, you want the behavior to be this: check for a customized swap function…if it exists, use it, if it does not exist, use the std library functions. In the cases where there are no customized swap functions available, you want it to default to the simple std::swap implementation described in the link above. Hence the “using”, to bring swap for built-in types into the namespace. But those will be tried last.

See also: https://stackoverflow.com/a/2684544/2012659

If for some reason you hate the “using std::swap”, I suppose you could in theory resolve this manually by explicitly calling std::swap for everything you’d want to swap using std::swap and using the unqualified swap for every custom swap you know is defined (still found using ADL). But this is error prone … if you didn’t author those classes you may not know if a customized swap exists for it. And switching between std::swap and swap makes for confusing code. Better to let the compiler handle all of this.

Leave a Comment