swap function under the hood

 

Swap function is such a nice method to swap between two values. This value can be valid C++ objects.
The standard swap function does the following, which could deal with any valid objects. The objects should have support for a copy constructor, operator = methods. The normal swap function looks as follows.

template<class _Ty> inline
 void swap(_Ty& _Left, _Ty& _Right)
 { // exchange values stored at _Left and _Right
 _Ty _Tmp = _Left;
 _Left = _Right, _Right = _Tmp;
 }

Many people claiming that standard swap functions in the std name space and of containers offers constant time for swapping between two objects specially the matter of containers. If we have a an object and if we are calling swap function, it will not have a constant swap time because we could write anything inside our object’s copy ctor and operator= which mainly involves in the swap process.

In the matter of containers it’s optimal. ‘swap’ function have been customized by each containers according to it’s behavior.
For instance, if you get into the swap function of vector, you could see something as follows.

template<class _Ty, class _Alloc> inline
 void swap(vector<_Ty, _Alloc>& _Left, vector<_Ty, _Alloc>& _Right)
 { // swap _Left and _Right vectors
 _Left.swap(_Right);
 }

The above one is the swap function for vector container. It’s internally calling swap function of vector class. Which does the following.

void swap(_Myt& _Right)
{ // exchange contents with _Right
 if (this->_Alval == _Right._Alval)
 { // same allocator, swap control information
  std::swap(_Myfirst, _Right._Myfirst);
  std::swap(_Mylast, _Right._Mylast);
  std::swap(_Myend, _Right._Myend);
 }
 else
 { // different allocator, do multiple assigns
  _Myt _Ts = *this; *this = _Right, _Right = _Ts;
 }
}

The above function does the swap by exchanging its control information, no other allocations or objects are changed. It does the normal swap functionality, only if the allocator for the container is of different type. Thus it achieves the maximum speed.

But as I said before, if we are writing a new class and it has some lengthy processing in operator= or copy constructor, it could not achieve the maximum speed.

Keep this in your mind when you write your swap function next time and write swap function if your objects are constantly used to swap between.

Also try to offer a global swap function for your objects as the std containers does because, if you don’t write a swap function, there’s a chance users of your class to call the std::swap function which I mentioned very first. So that you can redirect it to your proper swap function instead of std::swap function calls executes copy constructor and operator= which you were not intended. Also std::swap function will never call your swap function. So customize it. See the snippet below.

e.g
void swap( CMyClass& left, CMyClass& right )
{
    left.Swap( right); // Direct to your swap function
}