1. Technology

Generic Solution to Freeing Objects in Delphi's TStrings

By July 11, 2011

Follow me on:

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 about Generic Solution to Freeing Objects in Delphi's TStrings

Related:

Comments
July 13, 2009 at 10:08 am
(1) Bruce McGee says:

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.

July 14, 2009 at 1:17 am
(2) Eric says:

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!

July 14, 2009 at 7:04 am
(3) Zarko Gajic says:

@Eric: Yep, you are right – will correct it. Thanks for noticing.

July 11, 2011 at 7:57 am
(4) Damien says:

I always use count-1 instead of Pred(count).. Is there a difference ? (in performance ?)

July 11, 2011 at 4:32 pm
(5) Paul says:

To avoid an exception if the object is not assigned, you should probably add:

if Assigned(strings.Objects[idx]) then
begin
strings.Objects[idx].Free;
strings.Objects[idx] := nil;
end;

July 11, 2011 at 5:56 pm
(6) Regan says:

This is the method I use (it is for TStringList instead of TStrings) but principle is the same:

procedure ClearStringList(AStringList: TStringList);
var
I: Integer;
begin
for I := 0 to AStringList.Count – 1 do
if Assigned(AstringList.Objects[i]) then
try
AstringList.Objects[i].Free;
except
on E: EAccessViolation do
AstringList.Objects[i] := nil
else
raise;
end;
AStringList.Clear;
end;

July 12, 2011 at 2:42 am
(7) Marjan Venema says:

In newer version of Delphi TStringList supports an AOwnsObjects parameter in the constructor which, if set to True, makes it free the objects in contains upon destruction. No need for any special code.

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

©2014 About.com. All rights reserved.