Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Object-Pascal / Delphi-Language (https://www.delphipraxis.net/32-object-pascal-delphi-language/)
-   -   Delphi Free Objects in List (https://www.delphipraxis.net/90489-free-objects-list.html)

Delphi-Lover 18. Apr 2007 14:05


Free Objects in List
 
Hello,

I just want to be sure about a thing I wonder about.
Normally to free objects added to a list I do the following:

Delphi-Quellcode:
//The object I add to the List
TMyListObject = Class(TObject)
        ID : Integer;
        Name : String;
End;

//The List
MyList : TStringlist;

//Add the Object in the list
Var aMyListObject : TMyListObject;

aMyListObject:=TMyListObject.Create;
aMyListObject.ID=1;
aMyListObject.Name='Example';

MyList.AddObject('1',aMyListObject);
Normally When I want to free the objects in the list I cast the ListObject in the Free Like:

Delphi-Quellcode:
Var Index : Integer;
Begin
  For Index:=0 to MyList.Count-1 do
  Begin
    TMyListObject(MyList.Objects[Index]).Free;
  End;
  MyList.Clear;
End;
Now I hear that casting is not needed and you can do it directly by the list.objects.free like:

Delphi-Quellcode:
var Index : Integer;
Begin
  for Index := 0 to MyList.Count - 1 do
  begin
    if Assigned(MyList.Objects[Index]) then
    begin
      MyList.Objects[Index].Free;
      MyList.Objects[Index]:=nil;
    end;
  end;
End;
Note, there is no destructor in the ListObject.
I thought you have to cast the listobject while freeing the List, but maybe this is not needed.

Thanks !

Delphi-Lover

Udontknow 18. Apr 2007 14:18

Re: Free Objects in List
 
Hello there!

As the method "Free" is implemented nonvirtual in the main ancestor class TObject, a call of "TListObject(MyObject).Free" is always equal to "MyObject.Free" and will cause a call to the destructor "Destroy". If you dont override the destructor of a descendant class, there is still the destructor "TObject.Destroy" that is inherited. Every object has at least this destructor.

Cu,
Udontknow


Alle Zeitangaben in WEZ +1. Es ist jetzt 18:27 Uhr.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024-2025 by Thomas Breitkreuz