Sunday, June 10, 2007

item11

handle assignments to self in operator =

self assignment is likely to happen for e.g.
a[i] = a[j]
*pt = *pg

or some other way it will happen.

in resource management classes be esp aware of releasing current resources and self assignment causing trouble. imagine
widget& widget::operator=(const widget& rhs_
{
delete pb;
pb = new Bitmap)*rhs.pb);
}

u can use if( this = &rhs) then return at top of function for this.

also the above is exception unsafe....pb will point to a deleted object if new Bitmap throws exception

so use combination of save elsewhere, copy new, delete elsewhere to avoid exception ....that makes it self assignment safe too

one thing is if someone else kept a ptr to this pb then self assignment has caused a complete copy to happen...also the new address is different from older address ( old pb[2] isnt same as new pb[2]) ....does this make sense ?

things to remember:
make sure operator= is well behaved when an object is assigned to itself techniques include comparing addresses of source and target objects, careful stmt ordering and copy and swap

make sure that any function operating on more than one object behaves correctly if two or more of the objects are the same,

No comments: