C 記憶體管理 part2

2021-06-22 15:10:55 字數 3046 閱讀 3209

allocating class instances using new

new operator 也可以用於對class instance分配動態記憶體。

如下例:

#include using namespace std;

class point

private:

int x;

int y;

};int main()

執行結果如下:

再比如, 我們定義乙個有引數的constructor:

#include using namespace std;

class point

point(int nx, int ny)

private:

int x;

int y;

};int main()

執行結果

destructor(解構子)

當我們的class instance 被deallocated 的時候, 就會呼叫destructor。

如下:

class point 

point(int nx, int ny)

~point()

private:

int x;

int y;

};

全體程式如下:

#include using namespace std;

class point

point(int nx, int ny)

~point()

private:

int x;

int y;

};int main()

執行之後, 得到:

注意, 如果採用new 為物件動態分配記憶體時, 必須採用delete, 才會呼叫destructor。 如上。

如果物件是stack-allocated, 當物件goes out of scope, 才會呼叫解構子。

#include using namespace std;

class point

point(int nx, int ny)

~point()

private:

int x;

int y;

};int main()

cout << "p out of scope" << endl;

return 0;

}

執行結構如下:

下面, 我們編寫乙個類去representing an array of integers.。 不難看出, 成員變數不僅需要乙個指向陣列第乙個元素的指標, 也需要有陣列元素個數的資訊。

注意當建構子中使用了動態記憶體分配(new), 那麼在解構子中必須要釋放這些動態記憶體(delete)。 如果沒有分配動態記憶體, 那麼

解構子的函式體內可以什麼也不寫。

下面舉乙個例子:

#include using namespace std;

class integerarray

~integerarray()

};int main()

cout << a.data[0] << endl; // not 4, why????

return 0;

}

上述執行的結果為:

出錯, 下面給出解釋:

也就是說, 當b goes out of scope, 就會呼叫的destructor, 用於deallocates array, 現在a.data 變成了乙個dangling pointer。

除此之外, 還有乙個bug, 就是當a goes out of scope, its constructor tries to delete (already deleted ) array。

如何消除這兩個bugs 呢? 解決辦法就是寫出乙個copy constructor(賦值建構子):

#include using namespace std;

class integerarray

//copy constructors

integerarray(integerarray &o)

}~integerarray()

};int main()

cout << a.data[0] << endl;

return 0;

}

執行結果如下:

分析見如下兩幅圖:

程式設計練習 part2

一.題目 對於乙個給定的井字棋棋盤,請設計乙個高效演算法判斷當前玩家是否獲勝。給定乙個二維陣列board,代表當前棋盤,其中元素為1的代表是當前玩家的棋子,為0表示沒有棋子,為 1代表是對方玩家的棋子。測試樣例 1,0,1 1,1,1 1,1,0 返回 true 思路 對於井字棋的獲勝方式,有下面幾...

網路程式設計part2

五層協議 計算機1 計算機2 應用層 應用層 socket socket 傳輸層 段傳輸層 網路層包 網路層資料鏈路層 幀資料鏈路層 物理層 互動機 物理層 客戶端軟體send 服務端軟體recv 作業系統 作業系統 計算機硬體 物理介質 計算機硬體 客戶端軟體send 服務端軟體recv 作業系統...

c 檔案分割與合併 part 2

同樣,引用system.io,然後,給瀏覽按鈕新增如下 瀏覽 private void button1 click object sender,eventargs e string path openfiledialog1.filename.split tochararray string stem...