Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I free an array of objects in a Delphi 7 destructor?

Suppose my Delphi classes look like this:

interface
type

    TMySubInfo = class
    public
        Name : string;
        Date : TDateTime;
        Age  : Integer;
    end;

    TMyInfo = class
    public
        Name : string;
        SubInfo : array of TMySubInfo;
        destructor Destroy; override;
    end;

implementation

    destructor TMyInfo.Destroy;
    begin
      // hmmm..
    end;

end.

To properly clean up, what should go in the destructor? Is it enough to do SetLength(SubInfo,0), or do I need to loop through and free each TMySubInfo? Do I need to do anything at all?

like image 836
Blorgbeard Avatar asked Feb 12 '09 23:02

Blorgbeard


1 Answers

You need to loop through and free each created object.

You must know, that declaring a array of TMySubInfo doesn't actually create the objects. You have to create them later on.

I would use a TList instead for a more dynamic approach. You could even use a TObjectList that can free all its items when the list gets freed.

like image 64
Vegar Avatar answered Oct 20 '22 00:10

Vegar