Do I need to free elements of a list?
Asked Answered
F

1

5

Hello I have a list of type TList. I fill it with pointer to records which are created with new.

One of my coworkers told me that freeing the list will free all elements, but I have my doubts because I'm use to C. So does Delphi 7 have some sort of garbage collection and I really don't have to free each element? Can someone explain to me how that works?

Frater answered 19/10, 2011 at 19:48 Comment(3)
A TList to hold records? Why not simply an array? Then you don't have the overhead of New and Dispose; just SetLength, ét voila.Lemaster
@Lemaster because it's size has to be determined at runtime.Frater
Earlz, Delphi supports dynamic arrays as of version 4. You can set its size at run time. It's not like C arrays (although even C arrays have been able to have their sizes determined at run time for the last decade or so).Zerla
Z
14

TList holds pointers, but it does not own the things they point at. It cannot, because it has no idea how you allocated them, so it cannot know how to release them, either. You need to destroy those items yourself, if they're supposed to be destroyed.

Your colleague might be thinking of TObjectList, which can optionally own the items in the list.

Zerla answered 19/10, 2011 at 19:51 Comment(1)
Since TList in this question holds pointers to records, it is important to call Dispose passing the pointer of the same type as was allocated with New - if allocated records hold compiler-managed types such as long strings and dynamic arrays.Trachytic

© 2022 - 2024 — McMap. All rights reserved.