Re: FreeAndNil
- From: "Tom de Neef" <tdeneef@xxxxxxxx>
- Date: Wed, 19 Jul 2006 09:53:47 +0200
"pri_sama" <pri_sama@xxxxxxxxx> schreef in bericht
news:1153281905.119034.68990@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
The Delphi 5 FreeAndNil procedure is as follows,
procedure FreeAndNil(var Obj);
var
P: TObject;
begin
P := TObject(Obj);
TObject(Obj) := nil; // clear the reference before destroying the
object
P.Free;
end;
Can someone tell me why hasn't it used,
procedure FreeAndNil(var Obj);
begin
TObject(Obj).Free;
TObject(Obj) := nil;
end;
You mean, why isn't it called NilAndFree ;-)
When you have a recursive process - such as freeing the nodes in an
intertwined tree - you must consider that the call to FreeAndNil will, via
its Tobject(Obj).free, call its own caller. To avoid an endless loop or AV
you'd use IF NOT assigned(obj) THEN FreeAndNil(obj);
But if the order of FREE and NIL would be as in your proposed procedure,
such a statement would not have the desired safe outcome.
Consider how the following program will loop forever if FreeAndNil is
replaced by your code.
type
Tnode = class
aNode : Tnode;
procedure free;
end;
procedure Tnode.free;
begin
if assigned(aNode)
then FreeAndNil(aNode)
end;
var
node : Tnode;
begin
node:=Tnode.create;
node.aNode:=node; // a trivial recursive tree
node.free; // this will loop if FreeAndNil has wrong order of things
end;
Tom
.
- Follow-Ups:
- Re: FreeAndNil
- From: Maarten Wiltink
- Re: FreeAndNil
- References:
- FreeAndNil
- From: pri_sama
- FreeAndNil
- Prev by Date: Re: FreeAndNil
- Next by Date: Re: FreeAndNil
- Previous by thread: Re: FreeAndNil
- Next by thread: Re: FreeAndNil
- Index(es):
Relevant Pages
|