Given the following Delphi code, Foo is Free‘d on FormClose, but TFoo.Destroy is not being called – and therefore Bar is not Free‘d, leading to a memory leak?
Have I missed something here or shouldn’t Foo.Free call Foo.Destroy at some point?
type
TBar = class
SomeInteger : integer;
end;
TFoo = class
Bar : TBar;
constructor Create();
destructor Destroy();
end;
var
Foo : TFoo;
implementation
constructor TFoo.Create;
begin
Bar := TBar.Create;
Bar.SomeInteger := 2;
end;
destructor TFoo.Destroy;
begin
Bar.Free;
Bar := nil;
showmessage('Destroyed!');
end;
procedure TForm10.FormCreate(Sender: TObject);
begin
Foo := TFoo.Create;
showmessage('Foo created');
end;
procedure TForm10.FormDestroy(Sender: TObject);
begin
Foo.Free;
Foo := nil;
end;
You must mark the signature of destructor with override.
And you should have
inheritedat the end of the destructor. But since your class is not derived from anything other than TObject I suspect that doesn’t matter.