您的位置:首页 > 运维架构

Deep copy and shallow copy

2016-06-22 14:35 387 查看
点击打开链接

明确两个基本概念:浅拷贝(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,你应当让这个类实现这个接口.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: