Swap and STL containers

Conceptually, swap is equivalent to the following operation:

template <typename T> void swap(T& x, T& y) {     T tmp(x);    x = y;    y = tmp;}

After the swap() is called, the contents of the x and y objects are swapped. This, however, is probably the worst possible way to actually implement swap. The first and most obvious problem with this implementation is that it copies both objects unnecessarily (it actually does three copy operations). The execution time of this operation is proportional to the size of the T type. For an STL container, the size would refer to the size of the actual container, not to the type of the element:

void swap(std::vector<int>& x, std::vector<int>& y) {    std::vector<int> tmp(x);    x = y; y = tmp; ...

Get Hands-On Design Patterns with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.