Search code examples
delphidelphi-7

What is the alternative to FreeAndNil in Delphi 7?


I have a doubt that whether FreeAndNil is the ideal approach to dispose an object . I have come across codes where something like

StringList1.Free; 
StringList1 := Nil;

is used. Is the above line an overkill , or is it a better way to do things ? What is the difference between the two approaches?


Solution

  • Strictly speaking, to dispose of an object you only need to call Destroy. However, if the reference is nil, ie. has not been assigned a pointer to a valid instance of an object, this would cause an access violation, so it's recommended to call Free instead which checks first if the passed reference is nil and does nothing in that case. FreeAndNil first assigns the passed reference to a temporary local variable, then assigns nil to the passed reference, then calls Free to dispose of the instance. The only difference between FreeAndNil and your sequence obj.Free; obj := nil; is that in the first case the passed reference will be nil even if the destructor raises an exception.