Chinaunix首页 | 论坛 | 博客
  • 博客访问: 359767
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-04-21 17:41:38

  •  deep copy shallow copy difference
C++ Notes: Shallow vs Deep Copies
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.
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.
  1. #include <iostream>
  2. using namespace std;

  3. class base {
  4.         public:
  5.                 int i;
  6.                 base() {i = 0;}
  7.                 base(int j) {i = j;}
  8. };

  9. int
  10. main(void)
  11. {
  12.         base *p1 = new base(23);
  13.         base *p2;
  14.         p2 = p1; // shallow copy
  15.         cout << "address of P1:" << p1 << endl;
  16.         cout << "value at P1:" << p1->i << endl;
  17.         cout << "address of P2:" << p2 << endl;
  18.         cout << "value at P2:" << p2->i << endl;
  19.         delete p2;
  20.         cout << "address of P1 after delete p2:" << p1 << endl;
  21.         cout << "value at P2 after deleteP2:" << p2->i << endl;

  22.         base O1(67);
  23.         base O2;
  24.         O2 = O1; // deep copy
  25.         cout << "value at O1:" << O1.i << endl;;
  26.         cout << "value at O2 after copy:" << O2.i << endl;

  27.         return (0);
  28. }
Result:
  1. value at P1:23
  2. address of P2:0x9922008
  3. value at P2:23
  4. address of P1 after delete p2:0x9922008
  5. value at P2 after deleteP2:0
  6. value at O1:67
  7. value at O2 after copy:67
阅读(952) | 评论(1) | 转发(0) |
0

上一篇:虚函数

下一篇:友元函数

给主人留下些什么吧!~~

onezeroone2011-04-24 16:16:56

dynamically allocated memory,