Basicaly the rule in Delphi is - if you create something you must destroy it.

While TForm distroys each of its child components you must remember that each Child Object is included in the Components list of the form. Therefore the Form knows about the components and can then destroy them each as it closes.

When you create a stringlist inside another class the class itself does not actually know about the string list (it only contains it) and therefore does not know that it needs to destroy it.

When I create a 'Map' object in my games I will typically register all child objects into the Map

[pascal]TBaseItem = Class;

TMap = Class
Items : TList;
Constructor Create;
Destructor Destroy;
Procedure AddItem(NewItem : TBaseItem);
End;

TBaseItem = Class
Map : TMap;
End;
[/pascal]

So Whenever a new item is created the Map.AddItem is called which adds it to the Items list.

When the Map is freed

[pascal]Destructor TMap.Destroy;
Var I : Integer;
Begin
For Items.Count-1 downto 0 do
Begin
TBaseItem(Items[I]).Free;
End;
End;
[/pascal]

Which ensures that the Map frees all the items in the same way that a form frees all the components that are on it.


If you create an instance of a class, you are responsible for freeing it.