The code snippet is suggested for C++98, there is another suggestion for C++11 (move semantics) in the same answer.
The reason why there is swap()
function for C++98 solution is very well explained in Scott Meyers' Effective C++ book.
Briefly;
template<typename T> // typical implementation of std::swap;
void swap(T& a, T& b) // swaps a's and b's values
{
T temp(a);
a = b;
b = temp;
}
As long as your types support copying (via copy constructor and copy
assignment operator), the default swap implementation will let objects
of your types be swapped without your having to do any special work to
support it.
However, the default swap implementation may not thrill you. It
involves copying three objects: a to temp, b to a, and temp to b. For
some types, none of these copies are really necessary. For such types,
the default swap puts you on the fast track to the slow lane.
Foremost among such types are those consisting primarily of a pointer
to another type that contains the real data. A common manifestation of
this design approach is the "pimpl idiom"...