0

这是从我的母语翻译过来的。
你有一堂课:

class Boo : public SuperBoo {
  Foo* fFoo1;
  Foo* fFoo2;
}

其中 Foo - 单态类和 Boo 拥有指针 fFoo1、fFoo2。
Boo 的重载分配运算符。

我的解决方案是:

class Foo
{
public:
    Foo()
    {}
};

class SuperBoo
{
public:
    virtual ~SuperBoo()
    {}
};

class Boo : public SuperBoo
{
public:
    Boo(const int f1_id, const int f2_id)
    {
        f1 = new Foo(f1_id);
        f2 = new Foo(f2_id);
    }
    ~Boo()
    {
        delete f1;
        delete f2;
    }
    /* C++11 only
    Boo(Boo&& other)
    {
        std::swap(*this, other);
    }
    */
    Boo(const Boo& other)
    {
        f1 = new Foo(*(other.f1));
        f2 = new Foo(*(other.f2));
    }
    Boo& operator=(Boo other)
    {
        std::swap(f1, other.f1);
        std::swap(f2, other.f2);
        return *this;
    }
private:
    Foo* f1;
    Foo* f2;
};

但雇主不喜欢它。这里有什么问题?感谢帮助。

4

1 回答 1

1

构造函数可以重写为:

Boo(const int f1_id, const int f2_id)
{
    std::unique_ptr<Foo> pf1 = new Foo(f1_id);
    f2 = new Foo(f2_id);

    f1 = pf1.release();
}

这样如果 f2 构造函数抛出,f1 就不会被泄露。

顺便说一句,复制构造函数应该遵循相同的规则。

于 2013-03-15T11:24:01.907 回答