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?
The advantage of
TObjectListover the regularTListis that if theTObjectList.OwnsObjectsproperty is set to true then it means that theTObjectListis maintaining the lifetime of the objects that have been added to it.Quote from the
TObjectListdocumentation:So, if you set your
TObjectListto 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
TObjectListwould 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.