std::swap from <algorithm> is implemented as a template, so that it can exchange the values ββof two variables of any given type. His prototype looks like this:
template <typename T> void swap(T& a, T& b);
A typical implementation is to save one value in a temporary one, copy the second value into the first variable, and then put the temporary value in the second variable. In C ++, this includes copy constructor and assignment operators.
For large objects, all this construction and copying can be expensive. So many objects, including most (all?) STL containers, have an overloaded implementation that works by exchanging multiple pointer values. Exchange pointers are very fast, and this avoids any possible crashes (for example, allocating memory while creating the copy constructor). Overloaded std::swap forward to a member function (often also called swap ). A member function has access to internal components, so it can use a more efficient approach. Overloading might look something like this (simplified):
template <typename T> void swap<vector<T> >(vector<T>& a, vector<T>& b) { a.swap(b); }
If you want to see the real code, you can view the std header files for your compiler and OS.
source share