Writing Our Own swap Function

We can override the default behavior of swap by defining a version of swap that operates on our class. The typical implementation of swap is:

class HasPtr {
    friend void swap(HasPtr&, HasPtr&);
    // other members as in § 13.2.1 (p. 511)
};
inline
void swap(HasPtr &lhs, HasPtr &rhs)
{
    using std::swap;
    swap(lhs.ps, rhs.ps); // swap the pointers, not the string data
    swap(lhs.i, rhs.i);   // swap the int members
}

We start by declaring swap as a friend to give it access to HasPtr’s (private) data members. Because swap exists to optimize our code, we’ve defined swap as an inline function (§ 6.5.2, p. 238). The body of swap calls swap on each of the data members of the given object. In this case, we first swap the pointers and then the int members of the objects bound to rhs and lhs.


Image Note

Unlike the copy-control members, swap is never necessary. However, defining swap can be an important optimization for classes that allocate resources.


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

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