How is the exchange in C ++

I'm just starting to learn metaprogramming, I'm wondering how to implement swap. Can someone help me and explain the idea of ​​traits in metaprogramming? thanks.

+4
source share
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. 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.

+10
source

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; } 
+3
source

All Articles