記憶體管理:範例
本文說明 MFC 執行如何框架配置和堆積配置這三種常見的每一個記憶體配置:
位元組陣列
資料結構
物件
陣列的配置位元組
配置陣列在框架的位元組。
定義陣列如下列程式碼所示。 陣列,其記憶體自動回收,當變數關閉它的範圍。
{ const int BUFF_SIZE = 128; // Allocate on the frame char myCharArray[BUFF_SIZE]; int myIntArray[BUFF_SIZE]; // Reclaimed when exiting scope }
將位元組陣列或任何基本資料型別) 在堆積
使用這個範例中顯示的陣列語法的 new 運算子:
const int BUFF_SIZE = 128; // Allocate on the heap char* myCharArray = new char[BUFF_SIZE]; int* myIntArray = new int[BUFF_SIZE];
解除配置從堆積的陣列
使用 delete 運算子如下:
delete [] myCharArray; delete [] myIntArray;
資料結構的配置
配置在框架中的資料結構。
定義結構變數:
struct MyStructType { int topScore; }; void MyFunc() { // Frame allocation MyStructType myStruct; // Use the struct myStruct.topScore = 297; // Reclaimed when exiting scope }
當它結束其範圍時,結構所佔用的記憶體回收。
配置在堆積的資料結構。
使用配置在堆積 new 和 delete 的資料結構解除配置它們,如下所示的範例:
// Heap allocation MyStructType* myStruct = new MyStructType; // Use the struct through the pointer ... myStruct->topScore = 297; delete myStruct;
物件的配置
配置在框架的物件
宣告物件如下:
{ CMyClass myClass; // Automatic constructor call here myClass.SomeMemberFunction(); // Use the object }
當物件完成其範圍時,物件的解構函式自動叫用。
配置在堆積上的物件
使用 new 運算子,將指標傳回物件,則會配置在堆積上的物件。 使用 delete 運算子刪除它們。
下列堆積和架構範例假設, CPerson 建構函式不接受引數。
// Automatic constructor call here CMyClass* myClass = new CMyClass; myClass->SomeMemberFunction(); // Use the object delete myClass; // Destructor invoked during delete
如果 CPerson 建構函式的引數是指向 char,框架配置的陳述式是:
CMyClass myClass("Joe Smith");
堆疊配置的陳述式是:
CMyClass* myClass = new CMyClass("Joe Smith");