深度复制和浅复制的区别是什么?


当前回答

深拷贝

深度复制复制所有字段,并复制由字段指向的动态分配的内存。当对象与其引用的对象一起复制时,就会发生深度复制。

浅拷贝

浅复制是对象的逐位复制。创建一个新对象,该对象具有原始对象中值的精确副本。如果对象的任何字段是对其他对象的引用,则只复制引用地址,即只复制内存地址。

其他回答

什么是浅复制?

浅复制是对象的逐位复制。创建一个新对象,该对象具有原始对象中值的精确副本。如果对象的任何字段是对其他对象的引用,则只复制引用地址,即只复制内存地址。

In this figure, the MainObject1 has fields field1 of type int, and ContainObject1 of type ContainObject. When you do a shallow copy of MainObject1, MainObject2 is created with field2 containing the copied value of field1 and still pointing to ContainObject1 itself. Note that since field1 is of primitive type, its value is copied to field2 but since ContainedObject1 is an object, MainObject2 still points to ContainObject1. So any changes made to ContainObject1 in MainObject1 will be reflected in MainObject2.

如果这是浅复制,我们看看什么是深复制?

什么是深度复制?

深度复制复制所有字段,并复制由字段指向的动态分配的内存。当对象与其引用的对象一起复制时,就会发生深度复制。

在这个图中,MainObject1具有类型为int的字段field1和类型为ContainObject的字段ContainObject1。在对MainObject1进行深度复制时,MainObject2创建时,field2包含从field1复制的值,而ContainObject2包含从ContainObject1复制的值。注意,MainObject1中对ContainObject1所做的任何更改都不会反映在MainObject2中。

篇好文章

浅拷贝尽可能少地复制。集合的浅拷贝是集合结构的副本,而不是元素的副本。使用浅拷贝,两个集合现在共享单个元素。

深度复制复制一切。集合的深层副本是两个集合,原始集合中的所有元素都被复制。

The copy constructor is used to initialize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory. In order to read the details with complete examples and explanations you could see the article C++ constructors.

除了上述所有定义之外,还有一个最常用的深度复制,位于类的复制构造函数(或重载赋值操作符)中。

浅复制——>是当你没有提供复制构造函数时。在这里,只复制对象,但不复制类的所有成员。

深度复制——>是当您决定在类中实现复制构造函数或重载赋值,并允许复制类的所有成员时。

MyClass& MyClass(const MyClass& obj) // copy constructor for MyClass
{
          // write your code, to copy all the members and return the new object
}
MyClass& operator=(const MyClass& obj) // overloading assignment operator,
{
          // write your code, to copy all the members and return the new object
}

浅克隆: 定义:“对象的浅拷贝复制‘主’对象,但不复制内部对象。” 当一个自定义对象(例如。雇员)只有原始的,字符串类型的变量,然后你使用浅克隆。

Employee e = new Employee(2, "john cena");
Employee e2=e.clone();

返回super.clone();在重写的clone()方法中,您的工作就结束了。

深克隆: 定义:“与浅拷贝不同,深拷贝是对象的完全独立副本。” 表示当一个Employee对象持有另一个自定义对象时:

Employee e = new Employee(2, "john cena", new Address(12, "West Newbury", "Massachusetts");

然后,您必须在覆写的clone()方法中编写代码来克隆'Address'对象。否则Address对象不会被克隆,当你在克隆的Employee对象中改变Address的值时,它会导致一个错误,这也反映了原始的一个。