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)};inlinevoid 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
Get C++ Primer, Fifth Edition 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.