Free TObjectList declared as TList

184 Views Asked by At

How should the list (and its objects) declared as

var 
   myList: TList;

and created as

myList := TObjectList.Create;

be freed?

Should the objects be freed separately in a loop, as in a simple TList, or will myList.Free also free the objects in the list, since it was created as TObjectList?

1

There are 1 best solutions below

3
SilverWarior On

The advantage of TObjectList over the regular TList is that if the TObjectList.OwnsObjects property is set to true then it means that the TObjectList is maintaining the lifetime of the objects that have been added to it.

Quote from the TObjectList documentation:

Use TObjectList to store and maintain a list of objects. TObjectList provides properties and methods to add, delete, rearrange, locate, access, and sort objects. If the OwnsObjects property is set to true (the default), TObjectList controls the memory of its objects, freeing an object when its index is reassigned; when it is removed from the list with the Delete, Remove, or Clear method; or when the TObjectList instance is itself destroyed.

So, if you set your TObjectList to own its objects (which is its default behavior), upon its destruction it will automatically destroy each object in its list.

The exception would be if you are using a Delphi version with Advanced Reference Counting for objects 1. The TObjectList would only reduce the reference count for the objects that it owns. So, if such objects are also referenced somewhere else, they would not be destroyed until those additional references are also removed.

1: object ARC was used only for iOS and Android platforms. It was first introduced in Delphi XE4, but later removed in Delphi 10.4 Sydney, unifying the traditional object memory management model on all platforms.