I always thought that the owner is responsible for destroying visual controls and that I can manually control destruction if I pass nil
as the owner.
Consider the following example:
TMyForm = class (TForm)
private
FButton : TButton;
end;
...
FButton := TButton.Create(nil); // no owner!!
FButton.Parent := Self;
I would expect this button to produce a memory leak but it doesn't and in fact the destructor of TButton
is called.
Further investigation showed that the TWinControl
destructor contains the following snippet of code:
I := ControlCount;
while I <> 0 do
begin
Instance := Controls[I - 1];
Remove(Instance);
Instance.Destroy;
I := ControlCount;
end;
which looks like it is destroying the child components (the ones with Parent
set to the control itself).
I was not expecting the parent control to destroy the control. Can anybody explain why this is happening? And who is destroying the object if I pass in an owner?