Chinaunix首页 | 论坛 | 博客
  • 博客访问: 482238
  • 博文数量: 35
  • 博客积分: 4010
  • 博客等级: 上校
  • 技术积分: 1234
  • 用 户 组: 普通用户
  • 注册时间: 2005-10-06 22:48
文章分类

全部博文(35)

文章存档

2008年(35)

我的朋友

分类: C/C++

2008-11-30 21:30:04

明确两个基本概念:浅拷贝(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,你应当让这个类实现这个接口.


阅读(3945) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~