August 2012
Intermediate to advanced
976 pages
30h 17m
English
swap FunctionWe 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
Read now
Unlock full access