Chinaunix首页 | 论坛 | 博客
  • 博客访问: 88275
  • 博文数量: 60
  • 博客积分: 4002
  • 博客等级: 中校
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-17 18:11
文章分类

全部博文(60)

文章存档

2011年(60)

我的朋友

分类: C/C++

2011-03-30 21:54:17


C++ Notes: Shallow vs Deep Copies
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 disastrous 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.
A class that requires deep copies generally needs:

  • A to either make an initial allocation or set the pointer to NULL.
  • A to delete the dynamically allocated memory.
  • A to make a copy of the dynamically allocated memory.
  • An to make a copy of the dynamically allocated memory.
阅读(190) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~