Deep copy(深拷贝)和shallow copy(浅拷贝)的区别

来源:互联网 发布:上海中小企业数据 编辑:程序博客网 时间:2024/04/30 03:43

         deep copy 和shallow copy 都是用于对象之间的拷贝,如果对象没有其他对象的引用时,deep copy和shallow copy是一样的,但是如果有,如果只是用swallow copy,拷贝副本当中的对象引用和原来的对象是指向同一个对象的,即一块内存区域,因此,原对象和副本只要有一个当中的对象引用改变,另一个也被改变了。但是有时候我们不想这种情况发生,因此我们需要在拷贝时把引用对象一并拷贝,也就是说副本和原本是独立的,而这就是deep copy。

下面这个例子是来自http://stackoverflow.com/questions/2657810/deep-copy-vs-shallow-copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

拷贝的一些成员可能会有和原始对象引用到相同的对象:

class X{private:    int i;    int *pi;public:    X()        : pi(new int)    { }    X(const X& copy)   // <-- copy ctor        : i(copy.i), pi(copy.pi)    { }};

Here, the pi member of the original and copied X object will both point to the same int.

在这个例子当中,原始对象和X对象中的pi指向一个相同的int.


Deep copy:

All members of the original are cloned. There are no shared objects:

原本中所有对象都被复制来了,他们(指原本和副本)没有共享对象:

class X{private:    int i;    int *pi;public:    X()        : pi(new int)    { }    X(const X& copy)   // <-- copy ctor        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!    { }};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.

这个例子,原来的对象和X对象的pi就指向不同的int对象了,但是他们两个有一样的值。


The default copy constructor (which is automatically provided if you don't provide one yourself)creates only shallow copies.

缺省的拷贝构造函数只是浅拷贝。


0 0
原创粉丝点击