Wiki copymirror

This is a mirror of the wiki at pascal.chat. Editing, history and sign-in are there.

FreeAndNil

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.

pascal
procedure FreeAndNil( var obj );

Example:

pascal
{$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:

text
 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

From the Free Pascal wiki, page "FreeAndNil", as it stood on 2020-12-27 after a change by Jouborg, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 2, last changed by WikiArchive .