首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

BCB 動態建立 VCL 控制項陣列 (一):雙重指標實作

     編輯:關於C++

問題起因

網友需動態建立一組按鈕做遊戲選單,使用 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;  // 雙重指標

Button1 OnClick:動態建立並顯示 4 個按鈕

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);
    }
}

Button2 OnClick:正確釋放所有資源

void __fastcall TForm1::Button2Click(TObject *Sender) {
    for (int i = 0; i < 4; i++)
        delete x[i];     // 先釋放每個控制項物件
    delete[] x;          // 再釋放指標陣列
}

核心流程總結

  1. 宣告:TControl **array; (雙重指標)
  2. 配置指標陣列:array = new TControl*[count];
  3. 逐項配置物件:for(i) array[i] = new TControl(...);
  4. 釋放順序:先 delete array[i]; 逐項釋放物件,再 delete[] array; 釋放指標陣列。

驗證結果

編譯執行:點擊 Button1 出現 4 個按鈕,點擊 Button2 完整消失且無記憶體洩漏。大功告成!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved