![]() |
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:
Normally When I want to free the objects in the list I cast the ListObject in the Free Like:
//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);
Delphi-Quellcode:
Now I hear that casting is not needed and you can do it directly by the list.objects.free like:
Var Index : Integer;
Begin For Index:=0 to MyList.Count-1 do Begin TMyListObject(MyList.Objects[Index]).Free; End; MyList.Clear; End;
Delphi-Quellcode:
Note, there is no destructor in the ListObject.
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; I thought you have to cast the listobject while freeing the List, but maybe this is not needed. Thanks ! Delphi-Lover |
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