wap() is one of those tricky algorithms that has several implementations, each of which offers its own advantages and disadvantages. In the following sections I will show why familiarity with these implementations may be beneficial, albeit for different reasons than you might think.
The Standard Template Library offers a ready-made generic swap() algorithm (in the form of std::swap() which is defined in <algorithm>). Still, there are several other implementations of this algorithm. How do you choose which implementation to use? On which criteria should your evaluation be based?
Familiarize yourself with other implementations of swap(). Then, base your evaluation on the following criteria: performance, ease of maintenance, and genericity.
Step 1: Textbook swap()
The implementation of the plain, vanilla swap() algorithm is straightforward: take two arguments of the same type, copy the first one to a temporary variable, assign the second to the first, and finally, assign the temporary value to the second. Here is the complete function template:
template<class T> void v_swap(T& t1, T& t2)//plain vanilla
This implementation has a prominent advantage: it's generic
. As such, it's applicable to built-in types and user-defined types alike. Not very surprisingly, this is exactly how the std::swap() is implemented so there's no need to reinvent the wheel if you wish to use this version. What about performance? In order to evaluate it, let's compare this implementation to other implementations.