fischermx
asked on
Free and Nil..... or Nil and Free.....
Hi,
I have a basic Delphi question.
I've seen code where people use
However the FreeAndNil function code is this:
Which seems to first nil the object, then free it.
As opposite as what I've seen in other's people code where in separate lines they write Free first, then set it to Nil
Are both ways okey?
If not, why?
Please elaborate :)
I have a basic Delphi question.
I've seen code where people use
FreeAndNil(MyObject);
Some times other people writeMyObject.Free();
MyObject := nil;
However the FreeAndNil function code is this:
procedure FreeAndNil(var Obj);
var
Temp: TObject;
begin
Temp := TObject(Obj);
Pointer(Obj) := nil;
Temp.Free;
end;
Which seems to first nil the object, then free it.
As opposite as what I've seen in other's people code where in separate lines they write Free first, then set it to Nil
Are both ways okey?
If not, why?
Please elaborate :)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
This is a good resource for learning about the difference between Free and FreeAndNil...
Which is preferable: Free or FreeAndNil?
http://stackoverflow.com/questions/3159376/which-is-preferable-free-or-freeandnil
Which is preferable: Free or FreeAndNil?
http://stackoverflow.com/questions/3159376/which-is-preferable-free-or-freeandnil
For what it's worth: I normally only use FreeAndNil if it has a documenting purpose. In other words, if the logic of the code will make use of the same object (or whatever) again. If this is not the case it has no purpose to use FreeAndNil() instead of Free().
So if I see a FreeAndNil() in my code, I know something special is going on and somewhere further down the logic a piece of code needs to know the state (freed or not) of an object for some reason.
So if I see a FreeAndNil() in my code, I know something special is going on and somewhere further down the logic a piece of code needs to know the state (freed or not) of an object for some reason.
Setting a reference to a object = nil also clears the reference count
allowing it to free the object > used with com objects