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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.