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 the 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 that member function).

Finally, while the preferred invocation of the non-member swap is without the std:: prefix, the alternative use, although ill-advised, is common enough that an implicit instantiation of the std::swap template should be considered.

The next chapter takes us on a tour of one of the most popular, and powerful, C++ idioms—the C++ way of managing resources.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.44.52