Search code examples
delphipointersdelphi-xe6

Delphi: Is this code a correct procedure of nulling a pointer in FormClose?


IDE: Delphi XE6.

My main form creates another form and that form creates an instance of TFormZoom. All seems to work flawlessly.

I just want to be sure my procedure of nulling a pointer in FormClose is not distorting some inner workings of Delphi.

procedure TFormZoom.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Action := caFree;

  // if I did not set it to nil here, the next time I would create this form I would get
  // EAccessViolation, because my other code checks for this form <> nil ...

  FormZoom := nil;
end;

I am now thinking about, whether this approach is good. I don't get any compilation, nor run-time errors, this question is just a technicality.


Solution

  • If you set a breakpoint at the end; of TFormZoom.FormClose, and use F8 to step into the VCL code that called your onclose event handler, you'll see that it was called from TCustomForm.DoClose which was previously called from TCustomForm.Close. At that point in time, the following code can be seen (in Delphi 10.2.3)

    DoClose(CloseAction);
    if CloseAction <> caNone then
    if Application.MainForm = Self then Application.Terminate
    else if CloseAction = caHide then Hide
    else if CloseAction = caMinimize then WindowState := wsMinimized
    else Release;
    

    Because you set the Action var to caFree, it means the form's .Release will be called by the VCL code. My conclusion is: setting the global var FormZoom to nil, will not cause any problems.