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


当前回答

我想给出一个例子,而不是正式的定义。

var originalObject = { 
    a : 1, 
    b : 2, 
    c : 3,
};

这段代码显示了一个浅拷贝:

var copyObject1 = originalObject;

console.log(copyObject1.a);         // it will print 1 
console.log(originalObject.a);       // it will also print 1 
copyObject1.a = 4; 
console.log(copyObject1.a);           //now it will print 4 
console.log(originalObject.a);       // now it will also print 4

var copyObject2 = Object.assign({}, originalObject);

console.log(copyObject2.a);        // it will print 1 
console.log(originalObject.a);      // it will also print 1 
copyObject2.a = 4; 
console.log(copyObject2.a);        // now it will print 4 
console.log(originalObject.a);      // now it will print 1

这段代码显示了一个深度拷贝:

var copyObject2 = Object.assign({}, originalObject);

console.log(copyObject2.a);        // it will print 1 
console.log(originalObject.a);      // it will also print 1 
copyObject2.a = 4; 
console.log(copyObject2.a);        // now it will print 4 
console.log(originalObject.a);      // !! now it will print 1 !!

其他回答

char * Source = "Hello, world.";

char * ShallowCopy = Source;    

char * DeepCopy = new char(strlen(Source)+1);
strcpy(DeepCopy,Source);        

“ShallowCopy”指向与“Source”相同的内存位置。 “DeepCopy”指向内存中的不同位置,但内容是相同的。

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

为了便于理解,你可以参考这篇文章: https://www.cs.utexas.edu/~scottm/cs307/handouts/deepCopying.htm


浅拷贝:


深拷贝:

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.

尤其是iOS开发者:

如果B是a的浅拷贝,那么对于原语数据,它就像B = [a assign];对于对象,B = [A retain];

B和A指向同一个内存位置

如果B是a的深层副本,则B = [a copy];

B和A指向不同的内存位置

B的内存地址与A的相同

B和A的含量相同