具有依赖指针的类的复制赋值运算符
我正在做一个练习,其中我应该为一个类实现一个复制赋值运算符,如下所示:
class Foo : public SuperFoo {
Bar* fBar1;
Bar* fBar2;
~Foo() {delete fBar1; delete fBar2;}
// members without importance for the task.
};
Bar 类具有成员 Bar::Bar(const Bar&) 和 Bar& 。 Bar::operator=(const Bar&) 并且不是多态的。在建议的解决方案中,它提出了两种实现方式
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;
}
,
Foo& Foo::operator=(const Foo& that)
{
SuperFoo::operator=(that);
*fBar1 = *that.fBar1;
*fBar2 = *that.fBar2;
return *this;
}
第二个实现方式是指针“不相互依赖”。这意味着什么?我可以看到第一个实现中发生了什么,但我不明白何时以及为什么要这样做。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论