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


当前回答

尤其是iOS开发者:

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

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

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

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

B的内存地址与A的相同

B和A的含量相同

其他回答

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

浅拷贝尽可能少地复制。集合的浅拷贝是集合结构的副本,而不是元素的副本。使用浅拷贝,两个集合现在共享单个元素。

深度复制复制一切。集合的深层副本是两个集合,原始集合中的所有元素都被复制。

char * Source = "Hello, world.";

char * ShallowCopy = Source;    

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

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

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


浅拷贝:


深拷贝:

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

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