13.3. Swap

In addition to defining the copy-control members, classes that manage resources often also define a function named swap9.2.5, p. 339). Defining swap is particularly important for classes that we plan to use with algorithms that reorder elements (§ 10.2.3, p. 383). Such algorithms call swap whenever they need to exchange two elements.

If a class defines its own swap, then the algorithm uses that class-specific version. Otherwise, it uses the swap function defined by the library. Although, as usual, we don’t know how swap is implemented, conceptually it’s easy to see that swapping two objects involves a copy and two assignments. For example, code to swap two objects of our valuelike HasPtr class (§ 13.2.1, p. 511) might look something like:

HasPtr temp = v1; // make a temporary copy of the value of v1
v1 = v2;          // assign the value of v2 to v1
v2 = temp;        // assign the saved value of v1 to v2

This code copies the string that was originally in v1 twice—once when the HasPtr copy constructor copies v1 into temp and again when the assignment operator assigns temp to v2. It also copies the string that was originally in v2 when it assigns v2 to v1. As we’ve seen, copying a valuelike HasPtr allocates a new string and copies the string to which the HasPtr points.

In principle, none of this memory allocation is necessary. Rather than allocating new copies of the string, we’d like swap to swap the pointers. That is, we’d like swapping two HasPtrs to execute as:

string *temp = v1.ps; // make a temporary copy of the pointer in v1.ps
v1.ps = v2.ps;        // assign the pointer in v2.ps to v1.ps
v2.ps = temp;         // assign the saved pointer in v1.ps to v2.ps

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

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