Efficent way to swap

So, Here is the normal swap that we write which is inefficient as it makes a lot of copies.

swap(T& a, T& b) {
   T tmp {a};
   a = b;
   b = tmp;

So, what happens is that first value of “a” is copied inside “tmp”, then value of “b” is copied into “a” and finally value stored in “tmp” is copied into “b”. So ,there are  3 copies and data is moved 3 times which might not be a problem for int but it could be a problem for big structures.

So, Instead of copying values from one location to another we can just move the object but what is the difference between the move and copy? In both cases, the data is to be moved to new location.

So, how is it more efficient? It’s not in the case of static memory allocation but it is far more efficient in case of dynamic allocation of parts of the object. Just imagine that what would be more efficient.

  1. Moving 100 objects to the new location whose address we know.
  2. Change the address to point to the new location where objects are already stored.

Definitely the second option as in that case we need only to move address instead of 100 objects.

void swap(T& a, T& b) {
   T tmp {move(a)};
   a = move(b);
   b = move(tmp);

So, this is what happens went we use the move operator. Move operator converts the given lvalues into rvalues and then move the static values to new locations and change the pointers for Dynamic allocated parts. and we have efficient swap.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s