前言
TList 是 C++Builder VCL 框架中管理指標集合的核心類別,繼承自 TObject。它提供動態陣列功能,專門儲存物件指標,支援新增、刪除、排序、搜尋等操作。本文詳細說明其屬性、方法與最佳實踐。
類別繼承關係
TObject
└── TList
核心屬性
| 屬性 | 型別 | 說明 |
| Capacity | int | 內部指標陣列容量(配置大小),≥ Count |
| Count | int | 目前實際儲存的項目數 |
| Items[int Index] | void* | 索引器,存取指定位置的指標 |
| List | void** | 內部指標陣列的原始指標(少用) |
Capacity 與 Count 的關係
Capacity 是記憶體配置量,Count 是使用量
- 當
Count == Capacity 時再 Add,會自動擴充(通常加倍)
- 預先設定
Capacity 可避免重複配置,提升效能
// 高效新增大量項目範例
List->Clear();
List->Capacity = expectedCount; // 一次配置足夠記憶體
for (int i = 0; i < expectedCount; ++i)
List->Add(new MyObject(i)); // 無重新配置開銷
常用方法分類
新增與刪除
| 方法 | 說明 |
| Add(void* Item) | 尾端新增,回傳索引 |
| Insert(int Index, void* Item) | 指定位置插入 |
| Delete(int Index) | 刪除指定索引項目(不釋放物件記憶體) |
| Remove(void* Item) | 刪除第一個符合的指標,回傳索引 |
| Clear() | 移除所有項目(不釋放物件) |
| Pack() | 移除所有 NULL 指標,壓縮陣列 |
搜尋與排序
| 方法 | 說明 |
| IndexOf(void* Item) | 回傳首次出現索引,未找到為 -1 |
| Sort(TListSortCompare Func) | 快速排序,需提供比較函數 |
排序比較函數範例
int __fastcall CompareItems(void* Item1, void* Item2) {
MyClass* a = static_cast(Item1);
MyClass* b = static_cast(Item2);
return a->Value - b->Value; // 升序
}
List->Sort(CompareItems);
其他實用方法
| 方法 | 說明 |
| First() | 回傳 Items[0] |
| Last() | 回傳 Items[Count-1] |
| Exchange(int Index1, int Index2) | 交換兩項位置 |
| Move(int CurIndex, int NewIndex) | 移動項目位置 |
| Expand() | 手動擴充 Capacity |
| Error(const String& Msg) | 拋出 EListError 例外 |
記憶體管理關鍵提醒
⚠ TList 不會自動管理所指物件的生命週期!
Clear()、Delete()、Remove() 僅移除指標,不會 delete 物件
- 必須手動遍歷釋放:
for (int i=0;i
- 或使用
TObjectList(擁有 Ownership 機制)自動管理
現代化替代方案
C++11 後建議優先使用標準容器:
std::vector> — 擁有權語意、自動釋放、型別安全
std::vector> — 共享擁有權
std::list — 需頻繁中間插刪時
若維護舊專案需繼續用 TList,請嚴格遵守「誰建構誰釋放」原則,並善用 Pack() 清理 NULL 指標。