Main BLOGGER
Google
WWW THIS BLOG
Monday, January 22, 2007
 
two articles about C++ assignment operator
http://icu.sourceforge.net/docs/papers/cpp_report/the_anatomy_of_the_assignment_operator.html

class TFoo : public TSuperFoo { 
TBar* fBar1; //TBar is monomorphic (1)

TBar* fBar2;
// various method definitions go here...
}

//Do not need to be a virtual function 
TFoo& const
//considering: a=b=c and (a=b)=c
TFoo::operator=(const TFoo& that)
{
//step 1
if (this == &that) //compare address of this and that
retur *this;

//step 2
TBar* bar1 = 0; //make memory allocation a transaction
TBar* bar2 = 0;
try {
bar1 = new TBar(*that.fBar1);
//make a copy, see (1)
bar2 = new TBar(*that.fBar2);
TSuperFoo::operator=(that); //copy super's members
}
catch (...) {
delete bar1;
delete bar2;
throw;
}

//step 3
delete fBar1; //free fBar1
fBar1 = bar1;
//call TBar.=()
delete fBar2;
fBar2 = bar2;

//step 4
return *this;
}
(1) If TBar is polymorphic, we need a virtual function like clone() to accomplish the creation.
(2) Owning pointer: like fBar1, fBar2, whose lifecycle are the same as the host object of TFoo
--
Pop (Pu Liu)



<< Home

Powered by Blogger

Google
WWW THIS BLOG