深度复制和浅复制的区别是什么?
当前回答
我想给出一个例子,而不是正式的定义。
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 !!
其他回答
浅拷贝尽可能少地复制。集合的浅拷贝是集合结构的副本,而不是元素的副本。使用浅拷贝,两个集合现在共享单个元素。
深度复制复制一切。集合的深层副本是两个集合,原始集合中的所有元素都被复制。
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
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
char * Source = "Hello, world.";
char * ShallowCopy = Source;
char * DeepCopy = new char(strlen(Source)+1);
strcpy(DeepCopy,Source);
“ShallowCopy”指向与“Source”相同的内存位置。 “DeepCopy”指向内存中的不同位置,但内容是相同的。