Implementing swap

We have seen that all STL containers, and many other standard library types (for example, std::thread), provide a swap() member function. While not required, it is the easiest way to implement swap that needs access to the private data of the class, and also the only way to swap an object with a temporary object of the same type. The proper way to declare the swap() member function is like this:

class C {    public:    void swap(C& rhs) noexcept;};

Of course, the noexcept specification should only be included if a no-throw guarantee can indeed be given; in some cases, it may need to be conditional, based on properties of other types.

How should the swap be implemented? There are several ways. For many classes, we can simply swap ...

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.