【发布时间】:2019-03-26 09:55:12
【问题描述】:
我正在尝试对 Derived 类的对象 d 进行深层复制,如下面的代码所示:
class A {
public:
int m_int;
A* clone() {
return new A(*this);
}
};
class Base {
public:
A* m_a;
virtual Base* clone() {
A* new_a = new A();
new_a = this->m_a->clone();
Base* clone = new Base(*this);
clone->m_a = new_a;
return clone;
}
};
class Derived : public Base {
public:
double m_dbl;
virtual Derived* clone() {
return new Derived(*this);
}
};
int main() {
Derived* d = new Derived();
d->m_dbl = 1.234;
A* a = new A();
a->m_int = -1;
d->m_a = a;
//clone d
Derived d_copy = d->clone();
//changing values of d's attributes must not affect d_copy
a->m_int = 10;
d->m_dbl = 3.456;
//check d_copy
cout << "m_int " << d_copy->m_a->m_int << endl;
cout << "m_dbl " << d_copy->m_dbl << endl;
}
输出:
m_int 10 //wrong, should be -1;
m_dbl 1.234 //correct
如您所见,在 Derived 的 clone() 方法中简单地返回 new Derived(*this) 是错误的,因为它不会深度复制 m_a。
如果我将m_a从Base深度复制到Derived,那么我将得到正确答案:
virtual Base* clone() = 0;
...
virtual Derived* clone() {
A* new_a = new A();
new_a = this->m_a->clone();
Derived* clone = new Derived(*this);
clone->m_a = new_a;
return new Derived(*this);
}
//gives out m_int = -1
如果是这种情况,这是否意味着每次我从Derived 创建更多派生类时,我总是必须将clone() 的内容“还原”给他们?
另外,如果Base 有两个派生类Derived1 和Derived2,这是否意味着我必须在每个派生类中深度复制Base 的成员?
还有其他方法可以解决这个问题吗?
【问题讨论】:
-
为什么
m_a是一个指针?如果它是一个对象,您将免费获得深层副本 -
Base::clone内存泄漏。 -
你为什么不做深拷贝的拷贝构造函数呢?毕竟,复制是他们的目的。
标签: c++ inheritance deep-copy