public friend swap member function

In the beautiful answer to the copy-and-swap-idiom there is a piece of code I need a bit of help:

class dumb_array
{
public:
    // ...
    friend void swap(dumb_array& first, dumb_array& second) // nothrow
    {
        using std::swap; 
        swap(first.mSize, second.mSize); 
        swap(first.mArray, second.mArray);
    }
    // ...
};

and he adds a note

There are other claims that we should specialize std::swap for our type, provide an in-class swap along-side a free-function swap, etc. But this is all unnecessary: any proper use of swap will be through an unqualified call, and our function will be found through ADL. One function will do.

With friend I am a bit on “unfriendly” terms, I must admit. So, my main questions are:

  • looks like a free function, but its inside the class body?
  • why isn’t this swap static? It obviously doesn’t use any member variables.
  • “Any proper use of swap will find out swap via ADL”? ADL will search the namespaces, right? But does it also look inside classes? Or is here where friend comes in?

Side-questions:

  • With C++11, should I mark my swaps with noexcept?
  • With C++11 and its range-for, should I place friend iter begin() and friend iter end() the same way inside the class? I think the friend is not needed here, right?

2 Answers
2

Leave a Comment