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


当前回答

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

其他回答

除了上述所有定义之外,还有一个最常用的深度复制,位于类的复制构造函数(或重载赋值操作符)中。

浅复制——>是当你没有提供复制构造函数时。在这里,只复制对象,但不复制类的所有成员。

深度复制——>是当您决定在类中实现复制构造函数或重载赋值,并允许复制类的所有成员时。

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);
}

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.

摘自[博客]: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.

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

在面向对象编程中,类型包括成员字段的集合。这些字段可以按值或引用(即指向值的指针)存储。

在浅复制中,将创建该类型的新实例,并将值复制到新实例中。引用指针也像值一样被复制。因此,引用指向原始对象。对引用存储的成员的任何更改都同时出现在原始和副本中,因为没有对引用的对象进行复制。

在深度复制中,像以前一样复制按值存储的字段,但不复制按引用存储的对象指针。相反,对引用的对象进行深度复制,并存储指向新对象的指针。对这些引用对象所做的任何更改都不会影响该对象的其他副本。