Item 11-handling "self-assignment" (Handle assignment to the operator =) in operator =
"Self-assignment" occurs when an object is assigned to itself:
EX1:
Class widget{...}; Widget w;...w=w; Assign to yourself
Ex2: Create a class to hold a pointer to a dynamically allocated bitmap (bitmap)
Class bitmap{...}; Class widget{... ; Private: bitmap* PB; Pointer to an object allocated from the heap};
The following is implementation operator = implementation code, but self-assignment is not safe when it occurs
Widget &widget::operator = (const widget& RHS) //An unsafe operator = Implementation version { Delete pb; PB = new Bitmap (* RHS.PB) //Use a copy of RHS ' s Bitmap return *this;}
If operator = *this and RHS within a function are the same object, then delete does not just destroy the bitmap of the current object. It also destroys RHS and Bitmap,return to point to a deleted object.
Solution Solutions
1. operator = One of the first "certificates and tests" (Identity test)
widget& Widget::operator = (const widget& RHS) { if (this = &RHS) return *this //Identity Test
delete PB; PB = new Bitmap (* RHS.PB) return *this;}
2. Duplicate a copy and delete it
widget& Widget::operator = (const widget& RHS) { bitmap* porig = PB; Remember the original PB PB = new Bitmap (*RHS.PB); Make PB point to a duplicate of *PB delete porig; Delete the original PB return *this;}
3, ensure that the code is not only "exceptionally safe" and "self-assignment security", copy and Swap technology
Class widget{... void swap (widget& rhs); Exchange *this's RHS data}; widget& Widget::operator = (const widget& RHS) { Widget temp (RHS); Make a copy swap (temp) for RHS data; Exchange the *this data and the data of the above copy to return *this;}
Please remember:
Make sure that operator = good behavior when the object is self-assigned. The techniques include comparing the addresses of "source objects" and "target objects", the thoughtful sequence of statements, and the copy and swap.
Determines if any function operates on more than one object, and when multiple objects are the same object, its behavior is still correct.
Effective C + + Item 11-handling "self-assignment" in operator =