2

What is the copy-and-swap idiom? in this question, in the top answer, within the section where the swap public friend overload is implemented, the implementation makes use of this:

friend void swap(dumb_array& first, dumb_array& second){
    //the line of code below
    using std::swap;
    //then it calls the std::swap function on data members of the dumb_array`s
}

My question is the following: what is the using std::swap used for here (the answer mentions something related to enabling ADL); what use case of "using" is specifically being invoked here and what are the effects of adding that line of code and the effects of not adding it on the code?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Matias Chara
  • 921
  • 6
  • 21

1 Answers1

5

The using statement makes this line work:

swap(first, second);

Notice that we can omit std:: in front of swap.

The important thing there is that std::swap(...) is a qualified lookup, but swap(...) is an unqualified lookup. The main difference is that qualified lookup is calling a function in a specific namespace or scope (the one specified), whereas unqualified lookup is a bit more flexible since it will look into parent scope of the current context and also the global namespace. In addition, unqualified lookup will also look into the scope of the type of the arguments. It's a nice tool, but also dangerous since it can call function from unexpected places.

ADL will only work with unqualified lookup, since it has to search for other namespaces and scopes.

The using std::swap also ensure that if no function is found through ADL, it will call std::swap by default.

This idiom allow for user defined swap functions:

struct MyType {
    // Function found only through ADL
    friend void swap(MyType& l, MyType& r) {
        // ...
    }
};
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • If you could very briefly explain the differences between unqualified and qualified lookup I would be happy to accept your answer – Matias Chara Jul 03 '20 at 13:55