Re: FreeAndNil



"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


.



Relevant Pages

  • Re: FreeAndNil
    ... procedure FreeAndNil(var Obj); ... TObject:= nil; ... Alan Lloyd ...
    (comp.lang.pascal.delphi.misc)
  • Assigned and FreeAndNil
    ... procedure FreeAndNil(var Obj); ... Temp:= TObject; ... Pointer:= nil; ...
    (borland.public.delphi.non-technical)
  • Re: Remove the occurences of a given element from a list.
    ... (defun remvall (obj lst) ... REMOVE works just fine with NIL ...
    (comp.lang.lisp)
  • Re: JSON array, cant access result ?!?!
    ... correct technique for looping through an array anyway. ... the first seems to be from "for (var i in obj)", ... global scope completion routine was written because ...
    (comp.lang.javascript)
  • Re: How to decode a TNEF Stream?
    ... TStream; ExtractRTF: boolean); ... var Conv:TTNEFConverter; ... attAttachData: ... if LastAttach nil then SetAttachmentFileName(PChar ...
    (microsoft.public.win32.programmer.messaging)