深度复制和浅复制的区别是什么?
当前回答
广度vs深度;从引用树的角度考虑,将对象作为根节点。
浅:
变量A和B指的是不同的内存区域,当B被分配给A时,这两个变量指的是相同的内存区域。后来对其中一个内容的修改立即反映在另一个的内容中,因为它们共享内容。
深:
变量A和B指的是不同的内存区域,当B被分配给A时,A所指向的内存区域中的值被复制到B所指向的内存区域。后来对其中一项内容的修改仍为A或B所独有;内容不共享。
其他回答
摘自[博客]: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.
如果对象有任何指针,则需要执行深度复制。对于对象的深层拷贝,在自由存储区中为对象分配内存,并复制指向的元素。深度拷贝用于函数返回的对象。
我在这里没有看到一个简短的,容易理解的答案——所以我会试一试。
使用浅拷贝,源指向的任何对象也会被目标指向(因此不会复制引用的对象)。
使用深度复制,源指向的任何对象都将被复制,而目标指向的副本(因此现在每个引用的对象都有2个)。这是递归向下的对象树。
浅拷贝:将成员值从一个对象复制到另一个对象。
深度复制:将成员值从一个对象复制到另一个对象。 任何指针对象复制和复制。
例子:
class String
{
int size;
char* data;
};
String s1("Ace"); // s1.size = 3 s1.data=0x0000F000
String s2 = shallowCopy(s1);
// s2.size =3 s2.data = 0X0000F000
String s3 = deepCopy(s1);
// s3.size =3 s3.data = 0x0000F00F
// (With Ace copied to this location.)
浅复制-原始和浅复制对象中的引用变量引用公共对象。
深度复制-原始和深度复制对象中的引用变量引用不同的对象。
克隆总是做浅拷贝。
public class Language implements Cloneable{
String name;
public Language(String name){
this.name=name;
}
public String getName() {
return name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
主类如下-
public static void main(String args[]) throws ClassNotFoundException, CloneNotSupportedException{
ArrayList<Language> list=new ArrayList<Language>();
list.add(new Language("C"));
list.add(new Language("JAVA"));
ArrayList<Language> shallow=(ArrayList<Language>) list.clone();
//We used here clone since this always shallow copied.
System.out.println(list==shallow);
for(int i=0;i<list.size();i++)
System.out.println(list.get(i)==shallow.get(i));//true
ArrayList<Language> deep=new ArrayList<Language>();
for(Language language:list){
deep.add((Language) language.clone());
}
System.out.println(list==deep);
for(int i=0;i<list.size();i++)
System.out.println(list.get(i)==deep.get(i));//false
}
以上输出为-
假真假真 假假假
原始物体的任何变化都将反映在浅物体上,而不是在深物体上。
list.get(0).name="ViSuaLBaSiC";
System.out.println(shallow.get(0).getName()+" "+deep.get(0).getName());
输出- ViSuaLBaSiC C
假设有两个数组arr1和arr2。
arr1 = arr2; //shallow copy
arr1 = arr2.clone(); //deep copy