Self-assignment occurs when an object is assigned to itself:
Class widget {
...
}
Widget W;
...
W = W // assign a value to yourself
There is also an implicit example of self-assignment:
A [I] = A [J]; // when I = J
The following is a class:
Class bitmap {};
Class widget {
...
PRIVATE:
Bitmap * pb;
};
L version 1
Widget & Widget: Operator = (const widget & RHs ){
Delete Pb;
PB = new Bitmap (* RHS. Pb );
Return * this;
}
Note: There is a problem here, that is, if RHS refers to this object. After deleting Pb, the Pb of this is deleted.
To prevent such an error, you can add a certificate to the test:
L Version 2
Widget & Widget: Operator = (const widget & RHs ){
If (this = RHs) return * This; // same as test
Delete Pb;
PB = new Bitmap (* RHS. Pb );
Return * this;
}
This is acceptable, but another problem is that if an exception occurs during the new bitmap operation, the widget object will eventually hold a pointer to a deleted bitmap. Such pointers are harmful. You cannot safely delete them or read them.
However, this error can be avoided after careful arrangement:
L Version 3:
Widget & Widget: Operator = (const widget & RHs ){
Bitmap * OBJ = RHS. Pb;
PB = new Bitmap (* RHS. Pb );
Delete OBJ;
Return * this;
}
If a new bitmap exception occurs, petabytes remain unchanged. Note: although we have not added the same certification test, the aboveCodeYou can also handle the phenomenon of Self-assignment.
Version 4:
There is also a replacement version for Version 3:
Class widget {
Public:
...
Swap (widget & RHs );
PRIVATE:
Bitmap * pb;
};
Widget & Widget: Operator = (const widget & RHs ){
Widget temp (RHs );
Swap (temp );
Return * this;
}
This technology is called copy and swap technology.
- Remember:
- Make sure that operator = has good behavior when the object is assigned a value. Technologies include:
- Compare the addresses of "source object" and "target object"
- Careful and thoughtful statement order
- Copy and swap Technology
- Determine if any function operates on more than one object, and multiple objects are the same object, the behavior is correct.