Topic: Please tell us what is the deep and shallow copy copy? And implementation code to differentiate them.
【answer】
If a class have the resources, when the object of this class of objects that occur during replication occurs, the process can be called a deep copy, if there is a resource objects but does not copy the resource is shallow copy during the copying process.
[A]
Shallow copy follows:
class Test
{
public:
Test(int temp)
{
p=temp;
}
Test(Test &c_t)//自定义的拷贝构造函数
{
cout<<"进入copy构造函数"<<endl;
p=c_t.p1;//复制过程的核心语句
}
public:
int p1;
};
int main()
{
Test a(99);
Test b=a;
cout<<b.p1;
cin.get();
return 0;
}
Deep copy is also known as a deep copy of the object dynamic member, not just a simple assignment, but rather to re-allocate dynamic space.
Deep copy sample code is as follows:
class Rect
{
public:
Rect()//构造函数,p指向堆中分配空间
{
p=new int(100);
}
Rect(const Rect &r)
{
width=r.width;
height=r.height;
p=new int;//为新对象重新动态分配空间
*p=*(r.p);
}
~Rect()//析构函数,释放动态分配空间
{
if(p!=NULL)
{
delete p;
}
}
private:
int width;
int height;
int *p;
};
--