具有依赖指针的类的复制赋值运算符

发布于 2025-01-12 06:22:40 字数 1092 浏览 0 评论 0原文

我正在做一个练习,其中我应该为一个类实现一个复制赋值运算符,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文