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


当前回答

复制array:

Array是一个类,这意味着它是引用类型,因此array1 = array2的结果 在引用同一个数组的两个变量中。

但是看看这个例子:

  static void Main()
    {
        int[] arr1 = new int[] { 1, 2, 3, 4, 5 }; 
        int[] arr2 = new int[] { 6, 7, 8, 9, 0 };

        Console.WriteLine(arr1[2] + " " + arr2[2]);
        arr2 = arr1;
        Console.WriteLine(arr1[2] + " " + arr2[2]); 
        arr2 = (int[])arr1.Clone();
        arr1[2] = 12;
        Console.WriteLine(arr1[2] + " " + arr2[2]);
    }

浅克隆意味着只复制克隆数组所表示的内存。

如果数组包含值类型对象,则复制值;

如果数组包含引用类型,则只复制引用-因此有两个数组,其成员引用相同的对象。

要创建复制引用类型的深度复制,必须循环遍历数组并手动克隆每个元素。

其他回答

浅复制是创建一个新对象,然后将当前对象的非静态字段复制到新对象。如果字段是值类型——>,则执行字段的逐位复制;对于引用类型——>,引用被复制,但被引用的对象没有;因此,原始对象及其克隆对象引用同一个对象。

深度复制是创建一个新对象,然后将当前对象的非静态字段复制到新对象。如果字段是值类型——>,则执行字段的逐位复制。如果字段是引用类型——>,则执行引用对象的新副本。要克隆的类必须标记为[Serializable]。

我在这里没有看到一个简短的,容易理解的答案——所以我会试一试。

使用浅拷贝,源指向的任何对象也会被目标指向(因此不会复制引用的对象)。

使用深度复制,源指向的任何对象都将被复制,而目标指向的副本(因此现在每个引用的对象都有2个)。这是递归向下的对象树。

摘自[博客]:http://sickprogrammersarea.blogspot.in/2014/03/technical-interview-questions-on-c_6.html

深度复制涉及使用一个对象的内容创建同一类的另一个实例。在深度复制中,两个对象可能包含相同的信息,但目标对象将有自己的缓冲区和资源。任何一个对象的销毁都不会影响剩下的对象。重载赋值操作符将创建对象的深层副本。

浅拷贝包括将一个对象的内容复制到同类的另一个实例中,从而创建镜像。由于直接复制引用和指针,这两个对象将共享另一个对象的相同外部包含内容,这是不可预测的。

解释:

Using a copy constructor we simply copy the data values member by member. This method of copying is called shallow copy. If the object is a simple class, comprised of built in types and no pointers this would be acceptable. This function would use the values and the objects and its behavior would not be altered with a shallow copy, only the addresses of pointers that are members are copied and not the value the address is pointing to. The data values of the object would then be inadvertently altered by the function. When the function goes out of scope, the copy of the object with all its data is popped off the stack.

如果对象有任何指针,则需要执行深度复制。对于对象的深层拷贝,在自由存储区中为对象分配内存,并复制指向的元素。深度拷贝用于函数返回的对象。

简而言之,这取决于什么指向什么。在浅拷贝中,对象B指向对象a在内存中的位置。在深度复制中,对象A的内存位置中的所有东西都被复制到对象B的内存位置。

这篇wiki文章有一个很好的图表。

http://en.wikipedia.org/wiki/Object_copy

什么是浅复制?

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

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中。

篇好文章