CyprUS
CyprUS

Reputation: 4239

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?

Upvotes: 2

Views: 1103

Answers (2)

David Heffernan
David Heffernan

Reputation: 613282

The code in your question is probably written by someone that doesn't know about FreeAndNil. Or perhaps it was originally written before FreeAndNil was added to the RTL. If you want to nil the reference then you may as well use FreeAndNil. Writing it out longhand doesn't help.

The only real difference is that FreeAndNil will set the reference to Nil even if Free raises. But your destructors should never raise anyway so this is not that big a deal in my view.

There is a common trap with FreeAndNil. Because it takes an untyped parameter, you can pass it anything. For example you can pass an interface, a record etc. If you make this mistake then you usually end up with strange runtime errors.

I'm not going to get started on whether or not FreeAndNil is an appropriate design choice. That topic has been covered in some depth elsewhere.

Upvotes: 5

Ondrej Kelle
Ondrej Kelle

Reputation: 37221

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.

Upvotes: 9

Related Questions