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: Identifier like "_", "$", etc.
    ... The name of the framework is call "Underscore". ... obj.forEach(iterator, context); ... for (var key in obj) if (Object.prototype.hasOwnProperty.call ...
    (comp.lang.javascript)
  • Re: Object.create() // query
    ... You can use Object.create() if you see the "obj" object and want another ... var newObj = obj; ... var newObj = Object.create; ... it just uses horse as its prototype. ...
    (comp.lang.javascript)
  • Re: Remove the occurences of a given element from a list.
    ... (defun remvall (obj lst) ... REMOVE works just fine with NIL ...
    (comp.lang.lisp)