網友需動態建立一組按鈕做遊戲選單,使用 TList 卻無法正確釋放記憶體。TList::Clear() 僅清空列表,不釋放物件記憶體;delete 需要指標,但 TList 此用法難以取得原始指標。
嘗試標準 C++ 陣列語法失敗:
TSpeedButton *Buttons[] = new TSpeedButton[4](this); // 錯誤
TSpeedButton *Buttons[] = new TSpeedButton(this)[4]; // 錯誤
TSpeedButton []*Buttons = new TSpeedButton[](this); // Java 風格,錯誤
靈光一現:初始化列表語法可行但不適用大量控制項:
TSpeedButton *Buttons[] = { new TSpeedButton(this), new TSpeedButton(this), ... };
最終採用雙重指標分兩階段配置:
TSpeedButton **button = new TSpeedButton*[100]; // 1. 配置指標陣列
for (int i = 0; i < 100; i++)
button[i] = new TSpeedButton(this); // 2. 逐項配置物件
TSpeedButton **x; // 雙重指標
void __fastcall TForm1::Button1Click(TObject *Sender) {
x = new TSpeedButton*[4];
for (int i = 0; i < 4; i++) {
x[i] = new TSpeedButton(this);
x[i]->Left = 100;
x[i]->Top = 10 + i * 30;
x[i]->Width = 90;
x[i]->Height = 25;
x[i]->Parent = this;
x[i]->Caption = "按鈕" + AnsiString(i);
}
}
void __fastcall TForm1::Button2Click(TObject *Sender) {
for (int i = 0; i < 4; i++)
delete x[i]; // 先釋放每個控制項物件
delete[] x; // 再釋放指標陣列
}
TControl **array; (雙重指標)array = new TControl*[count];for(i) array[i] = new TControl(...);delete array[i]; 逐項釋放物件,再 delete[] array; 釋放指標陣列。編譯執行:點擊 Button1 出現 4 個按鈕,點擊 Button2 完整消失且無記憶體洩漏。大功告成!