Non-member swap

The standard also provides a template std::swap() function. Prior to C++11, it was declared in the <algorithm> header; in C++11, it was moved to <utility>. The declaration of the function is as follows:

template <typename T>
void swap (T& a, T& b);
template <typename T, size_t N>
void swap(T (&a)[N], T (&b)[N]); // Since C++11

The overload for arrays was added in C++11. In C++20, both versions are additionally declared constexpr. For STL containers, std::swap() calls the member function swap(). As we will see in the following section, the behavior of swap() can be customized for other types as well, but without any special efforts, the default implementation is used. This implementation does a swap using a temporary object. Before C++11, the temporary object was copy-constructed, and the swap was done with two assignments, just as we did in the preceding section. The type has to be copyable (both copy-constructible and copy-assignable), otherwise std::swap() will not compile. In C++11, std::swap() has been redefined to use move construction and move assignment. As usual, if the class is copyable, but does not have move operations declared at all, then the copy constructor and assignment are used. Note that if the class has copy operations declared and move operations declared as deleted, there is no automatic fallback to copying—that class is a non-movable type and std::swap() will not compile for it. 

Since copying an object can, in general, throw an exception, swapping two objects for which a custom swap behavior is not provided can throw an exception as well. Move operations do not usually throw exceptions, and in C++11, if the object has a move constructor and an assignment operator and neither throw an exception, std::swap() also provides the no-throw guarantee. That behavior has been formalized in C++17 with a conditional noexcept() specification.

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

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