DelphiBasics
freeandnil
Procedure
Free memory for an object and set it to nil SysUtils unit
 procedure freeandnil(var ObjectReference);
Description
The FreeAndNil procedure frees up the memory used by an object, and sets the object reference to nil.
 
It actually does this in reverse order - first dereferencing the object before deallocating the memory. This is a very clean way of freeing resources.
Related commands
FreeMemFree memory storage used by a variable
GetMemGet a specified number of storage bytes
NilA pointer value that is defined as undetermined
NullA variable that has no value
 Download this web site as a Windows program.




 
Example code : Free and nil an object, and then try to do this again
var
  myList : TList;

begin
  // Create the list object
  myList := TList.Create;

  // And now free and nil this object
  FreeAndNil(myList);

  // We can safely do this twice - it ignores nil objects
  FreeAndNil(myList);
end;
Show full unit code
  No exception occurs - the second FreeAndNil does nothing.
 
Delphi Programming © Neil Moffatt . All rights reserved.  |  Home Page