[fpc-pascal] Could someone explain me which the correct triggering of the BeforeDestruction method?

silvioprog silvioprog at gmail.com
Sun Sep 4 04:49:03 CEST 2016


Hello,

My question at title seems stupid, but the reason why I've get this doubt
is just because it get different results between Free Pascal and Delphi in
the following example:

=== begin code ===

program project1;

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$IFDEF MSWINDOWS}
  {$APPTYPE CONSOLE}
{$ENDIF}

uses SysUtils;

type
  TSomeClass = class
  public
    procedure LoadSomething;
  end;

  TA = class
  private
    FSomeObject: TSomeClass;
  public
    constructor Create; virtual;
    destructor Destroy; override;
    procedure AfterConstruction; override;
    procedure BeforeDestruction; override;
    property SomeObject: TSomeClass read FSomeObject;
  end;

procedure TSomeClass.LoadSomething;
begin
  raise Exception.Create('An exception loading something');
end;

constructor TA.Create;
begin
  WriteLn(1);
  inherited Create;
end;

destructor TA.Destroy;
begin
  WriteLn(2);
  inherited Destroy;
end;

procedure TA.AfterConstruction;
begin
  WriteLn(3);
  FSomeObject := TSomeClass.Create;
  FSomeObject.LoadSomething;
end;

procedure TA.BeforeDestruction;
begin
  WriteLn(4);
  FSomeObject.Free;
end;

var
  VA: TA;
begin
  VA := TA.Create;
  try
  finally
    VA.Free;
  end;
end.

=== end code ===

I've compiled it in Free Pascal from trunk (version 3.1.1 [2016/08/26] for
x86_64) installed on a Xubuntu 16.04 64 bits, and got the following log:

$ ./project1
1
3
2
An unhandled exception occurred at $00000000004001CD:
Exception: An exception loading something
  $00000000004001CD  LOADSOMETHING,  line 30 of project1.lpr
  $000000000040045A  AFTERCONSTRUCTION,  line 50 of project1.lpr
  $00000000004002CC  CREATE,  line 38 of project1.lpr
  $00000000004004FA  main,  line 62 of project1.lpr

and I've compiled the same code in an original version of Delphi Pro
(version 10.1 Berlin 24.0.22858.6822), on a Windows 10 64 bits, and I got
the log below and a critical exception (notice the result numbers, they are
different from similar test compiled in Free Pascal):

Win32\Debug>Project1.exe
1
3
4
2
^C

(I need to kill the app by Ctrl+C within terminal)

the critical exception was the known:

[Main Instruction]
Project1.exe has stopped working

[Content]
Windows is checking for a solution to the problem...

So, is it a bug? If so, in which compiler?! Even after reading some
documents about BeforeDestruction I still have doubt about which is the
correct triggering of this method, and I would be glad if someone could
help me to solve it.

--
Silvio Clécio
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-pascal/attachments/20160903/2f2879c7/attachment.html>


More information about the fpc-pascal mailing list