Summary
The swap functionality in C++ is used to implement several important patterns. The most critical one is the copy-and-swap implementation of exception-safe transactions. All standard library containers, and most other STL objects, provide the swap member function that is fast and, when possible, does not throw exceptions. User-defined types that need to support swap should follow the same pattern. Note, however, that implementing a non-throwing swap function usually requires an extra indirection and goes against several optimization patterns. In addition to the member function swap, we have reviewed the use and implementation of the non-member swap. Given that std::swap
is always available, and can be called on any copyable or movable objects, the programmer should take care to implement a non-member swap function too if a better way to swap exists for a given type (in particular, any type with a member function swap should also provide a non-member function overload that calls...