C++中的淺複製與深複製

轉載自 天之痕 

C++中的淺複製與深複製收藏

<script></script>

  默認構造函數將作爲參數傳入的對象的每個成員變量複製到新對象的成員變量中,這被稱爲成員淺複製。這雖然對大多數成員變量可行,但對於指向自由存儲區中對象的指針成員變量不可行。

  成員淺複製只是將對象成員變量的值複製到另一個對象中,兩個成員變量的指針最後指向同一個內存塊,當其中任何一個指針被delete時,將生成一個迷途指針,程序將處於危險之中。如圖:

 

  假如舊對象指針成員變量所指堆內存被釋放後,此時新對象指針成員變量仍指向該內存塊,這是不合法的。這種情況的解決辦法是:創建自己的複製構造函數並根據需要來分配內存。分配內存後,可以將原對象的值複製到新內存中。這稱之爲深層複製。

程序實例如下:

  1. #include <iostream>
  2. using namespace std;
  3. class Cat
  4. {
  5. public:
  6.   Cat();
  7.   Cat(const Cat &);
  8.   ~Cat();
  9.   int GetAge() const { return *itsAge; }
  10.   int GetWeight() const { return *itsWeight; }
  11.   void SetAge(int age) { *itsAge=age; }
  12. private:
  13.   int *itsAge;    //實際編程並不會這樣做,
  14.   int *itsWeight; //我僅僅爲了示範
  15. };
  16. Cat::Cat()
  17. {/*構造函數,在堆中分配內存*/
  18.   itsAge=new int;
  19.   itsWeight=new int;
  20.   *itsAge=5;
  21.   *itsWeight=9;
  22. }
  23. Cat::Cat(const Cat & rhs)
  24. {/*copy constructor,實現深層複製*/
  25.   itsAge=new int;
  26.   itsWeight=new int;
  27.   *itsAge=rhs.GetAge();
  28.   *itsWeight=rhs.GetWeight();
  29. }
  30. Cat::~Cat()
  31. {
  32.   delete itsAge;
  33.   itsAge=0;
  34.   delete itsWeight;
  35.   itsWeight=0;
  36. }
  37. int main()
  38. {
  39.   Cat Frisky;
  40.   cout << "Frisky's age: "<<Frisky.GetAge()<<endl;
  41.   cout << "Setting Frisky to 6.../n";
  42.   Frisky.SetAge(6);
  43.   cout << "Create Boots from Frisky/n";
  44.   Cat Boots=Frisky; //or Cat Boots(Frisky);
  45.   cout << "Frisky's age: " <<Frisky.GetAge()<<endl;
  46.   cout << "Boots' age : "<<Boots.GetAge()<<endl;
  47.   cout << "Set Frisky to 7.../n";
  48.   Frisky.SetAge(7);
  49.   cout << "Frisky's age: "<<Frisky.GetAge()<<endl;
  50.   cout << "Boots' age: "<<Boots.GetAge()<<endl;
  51.   return 0;
  52. }
  53. //輸出:
  54. //Frisky's age: 5
  55. //Setting Frisky to 6...
  56. //Create Boots from Frisky
  57. //Frisky's age: 6
  58. //Boots' age : 6
  59. //Set Frisky to 7...
  60. //Frisky's age: 7
  61. //Boots' age: 6
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章