FreeAndNil

From Free Pascal wiki
Jump to navigationJump to search

FreeAndNil is a procedure defined in the SysUtils unit of the Free Pascal Runtime Library. It calls an object's destructor (via TObject.Free) and also sets the object variable (which is a reference to heap memory created by a constructor call) to nil. If you just call an object's destructor, Assigned will still return True for the object variable. But after calling FreeAndNil, Assigned will return False for the object variable. While the procedure has an untyped parameter, it is only for use with object references - that is variables that are instances of a Class.

procedure FreeAndNil( var obj );

Example:

{$mode ObjFPC}
uses SysUtils;

type
   SomeClass = class(TObject)
      destructor Destroy; override;
   end;

destructor SomeClass.Destroy;
begin
   WriteLn('SomeClass Destructor called');
   inherited;
end;

var
   myClass : SomeClass;
   myClass2: SomeClass;
begin
   myClass  := SomeClass.Create;
   WriteLn('myClass is assigned? ', Assigned(myClass));
   myClass2 := SomeClass.Create;
   WriteLn('myClass2 is assigned? ', Assigned(myClass2));
   myClass.Destroy;
   WriteLn('myClass is assigned? ', Assigned(myClass));
   FreeAndNil(myClass2);
   WriteLn('myClass2 is assigned? ', Assigned(myClass2));
   // assigning Nil after destructor is called is the same as
   // FreeAndNil
   myClass := Nil;
   WriteLn('myClass is assigned? ', Assigned(myClass));
end.

Output:

 myClass is assigned? TRUE  
 myClass2 is assigned? TRUE
 SomeClass Destructor called
 myClass is assigned? TRUE
 SomeClass Destructor called
 myClass2 is assigned? FALSE
 myClass is assigned? FALSE