在这种情况下,如何正确实现“ operator =“和“ copy c'tor”?

时间:2018-07-09 07:10:37

标签: class c++11 operator-overloading copy-constructor derived-class

鉴于类BaseClassSomeClass(实现operator=copy c'tor),我编写了以下类:

class DerivedClass : public BaseClass {
 SomeClass* a1;
 SomeClass* a2;
public:
 // constructors go here …
 ~DerivedClass() { delete a1; delete a2;}
 // other functions go here ...
};

我的问题是:我如何实现类operator=的{​​{1}}?我如何实现此类的DerivedClass

我认为可以通过以下方式实现copy c'tor

operator=

但是我不确定该解决方案,特别是DerivedClass& operator=(const DerivedClass& d) { if (this==&d) return *this; SomeClass* tmp1 = new SomeClass (*(d.a1)); SomeClass* tmp2 = NULL; try { tmp2 = new SomeClass(*(d.a2)); } catch (const std::exception& e) { delete tmp1; throw e; } delete this->a1; delete this->a2; this->a1 = tmp1; this->a2 = tmp2; return *this; } 的字段如何?

此外,如何实现BaseClass中的copy c'tor?我可以用DerivedClass吗?

1 个答案:

答案 0 :(得分:1)

我的建议是您不要实施它们,而是去the rule of zero。这可以很容易地通过例如std::shared_ptr(如果可以接受a1a2的共享所有权)。

但是,如果必须实现自己的复制构造函数和复制赋值运算符,那么首先需要调用父类的构造函数或运算符,然后再进行自己的复制。

对于构造函数,请使用“构造函数初始化器”列表:

DerivedClass(DerivedClass const& other)
    : BaseClass(other), a1(new SomeClass(*other.a1)), a2(new SomeClass(*other.a2))
{}

a1(new SomeClass(*other.a1)部分使用其复制构造函数创建了一个新的SomeClass对象,并初始化了成员a1指向新对象。

这最后一部分也应该对您的拷贝分配运算符有所提示,因为它也可以在此处使用:

DerivedClass& operator=(DerivedClass const& other)
{
    if (this != &other)
    {
        // First let the parent copy itself
        BaseClass::operator=(other);

        // Deep copy of the members
        delete a1;
        a1 = new SomeClass(*other.a1);

        delete a2;
        a2 = new SomeClass(*other.a2);
    }

    return *this;
}