If the swapping of two strings can be optimized dramatically by using move semantics, imagine the effect of swapping two containers in this manner. Recall that containers also use swap()
implicitly, when they reallocate storage for new elements, for instance.
A copy-based container reallocation consists of these steps:
- Allocate a raw memory buffer that is large enough to accommodate the container's existing elements and the new ones.
- Copy-construct each element onto the new raw buffer.
- Destroy the original elements.
- Release the original memory buffer.
Unquestionably, this reallocation scheme is very expensive and slow.
The performance overhead of reallocation can be reduced drastically if the container moves its elements instead of copy-constructing them. Think of a vector of strings, for example. Instead of reallocating every string object using a copy-based swap, the vector can call move-based swap() to move strings from the original memory buffer to the new memory buffer. In other words, the newly constructed strings will simply swap their null buffer addresses and zero sizes with the original strings. Neither memory reallocation of string buffers nor character copying are required in this case.
Things get even better when you swap two containers. Theoretically, this operation would require member-wise copying of elements to a temporary container and a subsequent copying of each container's elements. You guessed it: a move operation can swap the contents of two containers by simply exchanging their data pointers and sizes. The performance improvement in this case is fantastic.