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 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.