• <table id="4yyaw"><kbd id="4yyaw"></kbd></table>
  • <td id="4yyaw"></td>
  • 發布時間:2020-09-28 23:05 原文鏈接: C++之拷貝構造函數的淺copy和深copy(三)

    輸出結果:

    root@txp-virtual-machine:/home/txp# g++ test.cpp
    root@txp-virtual-machine:/home/txp# ./a.out
    t1.i = 2, t1.j = 3, t1.p = 0x1528010
    t2.i = 2, t2.j = 3, t2.p = 0x1528010
    *** Error in `./a.out': double free or corruption (fasttop): 0x0000000001528010 ***
    Aborted (core dumped)

    注解:出現了段錯誤,仔細分析,我們發現這里釋放了堆空間兩次(因為我們這里沒有調用拷貝構造函數,也就是自己去寫拷貝構造函數;所以這種情況是淺拷貝,不能釋放兩次堆空間):

    代碼版本二(加上拷貝構造函數):

    #include <stdio.h>
    #include <string>
    class Test{
    private:
      int i;
      int j;
      int *p;
    public:
      int getI()
      {
         return i;
      }
      int getJ()
      {
         return j;
      }
      int *getP()
      {
         return p;
      }
      Test(int a)
      {
         i = 2;
         j = 3;
         p = new int;
         *p = a;
     }
     Test(const Test& t)
     {
       i = t.i;
       j = t.j;
       p = new int;
       *p = *t.p;
     }
     void free()
     {
       delete p;
     }
    };
    int main()
    {
      Test t1(4);
      Test t2 = t1;
      printf("t1.i = %d, t1.j = %d, t1.p = %p", t1.getI(), t1.getJ(), t1.getP());
      printf("t2.i = %d, t2.j = %d, t2.p = %p", t2.getI(), t2.getJ(), t2.getP());
      t1.free();
      t2.free();
      return 0;
    }


  • <table id="4yyaw"><kbd id="4yyaw"></kbd></table>
  • <td id="4yyaw"></td>
  • 调性视频