Clear a TList or a TObjectList

后端 未结 5 1420
故里飘歌
故里飘歌 2021-02-19 05:33

I\'m a bit puzzled of what to use for storing objects in a list. Until now I have used TList and freed each item in a loop. Then I discovered TObjectList

5条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 06:35

    1. TList won't free the elements, with both Clear or Free.

    aList.Clear;

    Will just set aList.Count := 0 without freeing the aList.Items[] elements. So you'll leak memory. You'll need an explicit free as such:

    for i := 0 to aList.Count-1 do
      TObject(aList[i]).Free;
    

    But this is what TObjectList does... :)

    About TObjectList, it is worth saying that TObjectList.Destroy is calling Clear.

    So

    aObjectList.Clear;
    aObjectList.Free;
    

    is exactly the same as

    aObjectList.Free;
    

    2. To store a list of records, you can use a dynamic array.

    You'll get all TList methods (and more) with our dynamic array wrapper. That is, Add / Delete / Clear / Count / IndexOf / Find...

    It has built-in serialization features (in binary or JSON), automated sorting and comparison (using RTTI) which are not existing with a TList/TObjectList. From Delphi 5 and later.

    With more modern version of Delphi, you may use generics to handle the dynamic array, if you do not want to use a third-party library.

提交回复
热议问题