深拷贝与浅拷贝 [英] Deep copy vs Shallow Copy

查看:171
本文介绍了深拷贝与浅拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

深层复制和浅层复制之间有什么区别?


深度和浅层副本之间有什么区别。

解决方案

浅拷贝:



副本的某些成员可能引用与原始对象相同的对象:

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

这里, pi 并复制 X 对象将指向相同的 int






深度复制



复制原稿的所有成员。没有共享对象:

  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))//< - 注意这一行!
{}
};

这里, pi 并且复制 X 对象将指向不同的 int 对象,但是这两个对象具有相同的值。






默认复制构造函数(如果您不自行提供,则会自动提供) 仅用于参考:虽然它只是一个很小的副本,但是它只创建了一个浅拷贝。





$ b <可能会读到一些小的隐藏,这里是1998年C ++标准第12.8节第8段所述的上述代码示例:


X 的隐式定义的复制
构造函数执行其子对象的
成员副本。
[...]每个子对象都以
的方式复制到它的类型:[...]
[I] f子对象是标量类型,
内置赋值运算符是



Possible Duplicate:
What is the difference between a deep copy and a shallow copy?

What is the difference between deep and shallow copy. What type of a copy does a copy constructor do?

解决方案

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.


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.


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


P.S.: Just for reference: While it may read a little cryptic, here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

这篇关于深拷贝与浅拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆