Generic Solution to Freeing Objects in Delphi's TStrings
Monday July 13, 2009
in Delphi TIPS :: Delphi TStrings object does not own the objects you add this way. Objects added to the TStrings object still exist even if the TStrings instance is destroyed. Objects must be explicitly destroyed by the application / developer - you; or your application will leak memory. Here's a generic solution to freeing the memory used by objects stored along strings in a TStrings descendant.
Read the full article to learn how to
Related:


Comments
Nice. I wrote something similar to empty string lists, including any owned objects as an alternative to TStringList.Clear.
It’s worth noting that Delphi 2009 added an “OwnsObjects” property to TStringList, similar to what’s already available in TObjectList.
The inner loop is somewhat incorrect, it should preferably be something like
strings.Objects[idx].Free;
strings.Objects[idx]:=nil;
so the object in the TStrings is nil’ed, and not just the local variable!
@Eric: Yep, you are right – will correct it. Thanks for noticing.