Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is swap implemented in c++

I just start learning metaprogramming, I wonder the implementation of swap. Can anyone help me and explain the idea of traits in metaprogramming? thanks.

like image 607
Rambo Avatar asked Dec 12 '22 19:12

Rambo


2 Answers

std::swap from <algorithm> is implemented as a template, so that it can exchange the values of two variables of any given type. Its prototype looks like this:

template <typename T> void swap(T& a, T& b);

The typical implementation is to save one value in a temporary, copy the second value to the first variable, and then to put the temporary value into the second variable. In C++, this involves a copy constructor and assignment operators.

For large objects, all of that construction and copying can be expensive. So many objects, including most (all?) of the STL containers have an overloaded implementation that works by exchanging a few pointer values. Exchanging pointers is very fast, and it avoids any potential failures (like memory allocation during the copy constructor). The overloaded std::swap forwards to a member function (often also called swap). The member function has access to the internals, so it can use a more efficient approach. The overload 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 browse the std header files for your compiler and OS.

like image 158
Adrian McCarthy Avatar answered Dec 30 '22 16:12

Adrian McCarthy


From http://www.cplusplus.com/reference/algorithm/swap/:

The behavior of this function template is equivalent to:

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}
like image 43
Oliver Charlesworth Avatar answered Dec 30 '22 17:12

Oliver Charlesworth