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 |
FreeMem |
|
Free memory storage used by a variable |
GetMem |
|
Get a specified number of storage bytes |
Nil |
|
A pointer value that is defined as undetermined |
Null |
|
A variable that has no value |
|
|
|
Example code : Free and nil an object, and then try to do this again |
// Full Unit code. // ----------------------------------------------------------- // You must store this code in a unit called Unit1 with a form // called Form1 that has an OnCreate event called FormCreate. unit Unit1; interface uses SysUtils, // Unit containing the FreeAndNil command Forms, Dialogs; type TForm1 = class(TForm) procedure FormCreate(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} // Include form definitions procedure TForm1.FormCreate(Sender: TObject); 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; end.
|
Hide full unit code |
No exception occurs - the second FreeAndNil does nothing.
|
|