Use std::swap ; he will do his best. If your compiler supports C ++ 11 rvalue references, this means that it will take advantage of the move semantics to avoid copying that occurs in your swap function.
However, if your compiler does not support rvalue links, it will most likely work just like your swap function.
Most standard library implementations implement std::swap as something similar to:
template<typename T> void swap(T& a, T& b) { T temp(std::move(a)); a = std::move(b); b = std::move(temp); }
The std::move function will return a reference to rvalue (T & &) to the passed variable. When you try to assign this rvalue reference, it will invoke a type-move operator, if one is available. If the move operator is not available, it will run the copy operator, as usual.
In the case of std::string aforementioned swap function will not contain string copies from C ++ 11; only internal data will be copied, such as the length of the string and the C pointer. Without C ++ 11, it will make three copies of the actual contents of the string.
source share