I’m doing an exercise in which I’m supposed to implement a copy-assignment operator for a class that looks as follows:
class Foo : public SuperFoo {
Bar* fBar1;
Bar* fBar2;
~Foo() {delete fBar1; delete fBar2;}
// members without importance for the task.
};
The Bar class has the members Bar::Bar(const Bar&) and Bar& Bar::operator=(const Bar&) and is not polymorphic. In the suggested solution it proposes two implementations
Foo& Foo::operator=(const Foo& that)
{
if (this != &that) {
Bar* bar1 = 0;
Bar* bar2 = 0;
try {
bar1 = new Bar(*that.fBar1);
bar2 = new Bar(*that.fBar2);
}
catch (...) {
delete bar1;
delete bar2;
throw;
}
SuperFoo::operator=(that);
delete fBar1;
fBar1 = bar1;
delete fBar2;
fBar2 = bar2;
}
return *this;
}
and
Foo& Foo::operator=(const Foo& that)
{
SuperFoo::operator=(that);
*fBar1 = *that.fBar1;
*fBar2 = *that.fBar2;
return *this;
}
The second is given that the pointers “doesn’t depend on one another”. What could this mean? I can see what is going on in the first implementation but I don’t understand when and why one would do it.