Using swap in Assignment Operators

Classes that define swap often use swap to define their assignment operator. These operators use a technique known as copy and swap. This technique swaps the left-hand operand with a copy of the right-hand operand:

// note rhs is passed by value, which means the HasPtr copy constructor// copies the string in the right-hand operand into rhsHasPtr& HasPtr::operator=(HasPtr rhs){    // swap the contents of the left-hand operand with the local variable rhs    swap(*this, rhs); // rhs now points to the memory this object had used    return *this;     // rhs is destroyed, which deletes the pointer in rhs}

In this version of the assignment operator, the parameter is not a reference. Instead, we pass the right-hand ...

Get C++ Primer, Fifth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.