[fpc-pascal] If an Assert fails in constructor, then destructor called (?)
Tom Verhoeff
T.Verhoeff at tue.nl
Wed Jul 1 12:17:10 CEST 2009
On Tue, Jun 30, 2009 at 07:58:47PM +0100, Inoussa OUEDRAOGO wrote:
> 2009/6/29 Tom Verhoeff <T.Verhoeff at tue.nl>:
> > While tracing a nasty bug (?), I discovered the hard way that when
> > an Assert is done in a constructor, and it fails, then the destructor
> > (Destroy) is automatically called.
>
> Indeed, when an exception is raised in the constructor, be it an
> "assert" exception or not, the destructor is called to allow the
> developer to clean up the "in-construction" instance's members he has
> already initialized.
A colleague of mine pointed out that the Delphi 7 documentation for
TObject.Create actually says so (see final Note):
Constructs an object and initializes its data before the object is first
used.
Delphi syntax:
constructor Create;
Description
Create constructs an object. The purpose, size, and behavior of objects
differ greatly. The Create constructor defined by TObject allocates memory
but does not initialize data.
Descendant objects usually define a constructor that creates the
particular kind of object and initializes its data.
Note: If an exception escapes from a constructor, the object's
destructor is called to clean up the failed instance.
Zoiets zou ook in de TObject.Create (RTL) doc. van FreePascal passen
(lees: thuishoren).
> > of the class methods to aid in tearing down the object. Except
> > that the object does not exist if the destructor gets called because
> > of the failed Assert in the constructor.
>
> Wrong. The object _does exists_ : its memory has been allocated and
> zeroed. With regard to the compiler/RTL, at the constructor entry
> point, the instance is valid. Please remember that the compiler is not
> aware of _your_ class invariants.
My apologies; it exists "technically" but may be "invalid"
(i.e. not a usable object, "semantically").
> Other important point : Object Pascal instance construction is not
> done the same way as in C++ where the object is completely constructed
> at the end of the constructor. In Object Pascal it is even valid to
> call virtual methods in the constructor, that is possible because at
> the constructor entry point the instance actual type is definitely
> fixed.
Thanks for the additional information.
Tom
--
E-MAIL: T.Verhoeff @ TUE.NL | Dept. of Math. & Comp. Science
PHONE: +31 40 247 41 25 | Technische Universiteit Eindhoven
FAX: +31 40 247 54 04 | PO Box 513, NL-5600 MB Eindhoven
http://www.win.tue.nl/~wstomv/ | The Netherlands
More information about the fpc-pascal
mailing list