深度复制和浅复制的区别是什么?
当前回答
除了上述所有定义之外,还有一个最常用的深度复制,位于类的复制构造函数(或重载赋值操作符)中。
浅复制——>是当你没有提供复制构造函数时。在这里,只复制对象,但不复制类的所有成员。
深度复制——>是当您决定在类中实现复制构造函数或重载赋值,并允许复制类的所有成员时。
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
}
其他回答
struct sample
{
char * ptr;
}
void shallowcpy(sample & dest, sample & src)
{
dest.ptr=src.ptr;
}
void deepcpy(sample & dest, sample & src)
{
dest.ptr=malloc(strlen(src.ptr)+1);
memcpy(dest.ptr,src.ptr);
}
“ShallowCopy”指向与“Source”相同的内存位置。“DeepCopy”指向内存中的不同位置,但内容是相同的。
试着考虑下面的图像
例如Object。memberwisclone创建一个浅复制链接
并使用ICloneable接口,你可以得到深度拷贝,如这里所述
浅复制-原始和浅复制对象中的引用变量引用公共对象。
深度复制-原始和深度复制对象中的引用变量引用不同的对象。
克隆总是做浅拷贝。
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
复制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]);
}
浅克隆意味着只复制克隆数组所表示的内存。
如果数组包含值类型对象,则复制值;
如果数组包含引用类型,则只复制引用-因此有两个数组,其成员引用相同的对象。
要创建复制引用类型的深度复制,必须循环遍历数组并手动克隆每个元素。