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


当前回答

假设有两个数组arr1和arr2。

arr1 = arr2;   //shallow copy
arr1 = arr2.clone(); //deep copy

其他回答

我从下面几句话中理解到。

浅拷贝将对象的值类型(int, float, bool)字段复制到目标对象中,对象的引用类型(字符串,类等)被复制为目标对象中的引用。在此目标引用类型将指向源对象的内存位置。

深度复制将对象的值和引用类型复制到目标对象的完整新副本中。这意味着值类型和引用类型都将被分配一个新的内存位置。

var source = { firstName="Jane", lastname="Jones" };
var shallow = ShallowCopyOf(source);
var deep = DeepCopyOf(source);
source.lastName = "Smith";
WriteLine(source.lastName); // prints Smith
WriteLine(shallow.lastName); // prints Smith
WriteLine(deep.lastName); // prints Jones

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

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

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

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
}

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.

假设有两个数组arr1和arr2。

arr1 = arr2;   //shallow copy
arr1 = arr2.clone(); //deep copy