Deep copy and shallow copy

来源:互联网 发布:c语言编写的程序 编辑:程序博客网 时间:2024/05/28 05:19

点击打开链接

明确两个基本概念:浅拷贝(Shallow Copy)与深拷贝(Deep Copy)

    1.浅拷贝(Shallow Copy)=(bitwise copy:位元逐一复制,按位拷贝)指的是拷贝对象而不拷贝该对象包含的对象,对它的嵌套的对象,仅拷贝其句柄。
    2.深拷贝(Deep Copy)指在拷贝对象的时候连同拷贝它所包含的对象

A shallow copy of an object copies all of the member field values. This works well if the fields are values, but may not be what you want for fields that point to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what you want. The default copy constructor and assignment operator make shallow copies.

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the original, with disasterous consequences.

Deep copies need ...
If an object has pointers to dynamically allocated memory, and the dynamically allocated memory needs to be copied when the original object is copied, then a deep copy is required.

    在c#的结构中自动实现了一种“memberwise“拷贝,也被称作“shallow copy”。object基类提供了一个protected方法,MemberwiseClone,来实现一个类成员的memberwise copy。

    如果类中的成员有一个或多个是引用类型,使用shallow copy 并不足够好。这将产生对相同数据的两个引用,而不是两个独立的数据副本。要拷贝数据自身而不是它的引用,你需要执行一个 “deep copy”.深度拷贝能够在语言级或类库级别上提供,c++通过语言级别的copy constructor来实现在c#中,deep copy是通过.net framework中的特定接口,ICloneable,提供。为了对一个类实现的deep copy,你应当让这个类实现这个接口.


0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 浴室门玻璃坏了怎么办 电梯顶层安全安全距离不合格怎么办 制冰机有些孔不出水怎么办 制冰机排水孔堵住了怎么办 点我达装备抽查怎么办 空军常服大檐帽有一点变形怎么办 一般纳税人没有进项发票怎么办 汽车购买发票丢了怎么办 购买房子的发票丢了怎么办 购买的二手房发票丢失怎么办 购买空调时的发票丢失怎么办 发票购票本丢了怎么办 留学中介费贵了怎么办 车祸伤者不肯出院怎么办 增值税普通发票发票联丢失怎么办 纳税识别号错了怎么办 电子发票税号填写错误怎么办 发票抬头名称写错了怎么办 滴滴发票抬头写错了怎么办 普票抬头开错了怎么办 发票号码打错了怎么办 个人税票开错了怎么办 普票地址错了怎么办 专票税率开高了怎么办 专票税率开错了怎么办 发票姓名写错了怎么办 首付发票姓名写错怎么办 一般纳税人税率开错了怎么办 电子税票开错了怎么办 税率是6%开成3%怎么办 医院收费收错了怎么办 发票少打一个字怎么办 增值税发票抬头错了一个字怎么办 暂估入账跨年了怎么办 电子发票写错了怎么办 发票纳税人识别号写错了怎么办 电子发票忘填邮箱怎么办 公司名跟发票抬头不一样怎么办 买空调不给发票怎么办 卖苹果手机没有发票怎么办 刷机字库刷坏了怎么办