Whether to use Free, or FreeAndNil, is an interesting topic. It depends on the circumstances.
My rule of thumb is that if an object is local (that is, it's reference variable will soon go out of scope) just use Free. But if the object is more "global," use FreeAndNil.
A classic example is a form that will create and show another form. This is often done within the scope of a button click handler, or an ActionItem's Execute method: procudure MyForm.Button1Click(Sender : TObject); var StudentForm : TStudentForm; begin StudentForm := TStudentForm.Create(Self); StudentForm.ShowModal; StudentForm.Free; end;
In the above snippet, the local variable, StudentForm, isn't accessible outside of the click handler, and it will go out of scope fairly soon. In this case, I think Free is sufficient.
However, if I'd made my reference variable more "global," say as a private member, FStudentForm, of TMyForm, any and every method of that class has access to it. In that case, I'll use FreeAndNil: procedure MyForm.Button1Click(Sender : TObject); begin if (FStudentForm = nil) then FStudentForm := TStudentForm.Create(Self); FStudentForm.ShowModal; FreeAndNil(FStudentForm); end;
Just to play it safe, you'll probably want to set FStudentForm to nil in TMyForm's OnCreate event.
Of course, it does no harm to use FreeAndNil wherever it's legal (As Mike says, the argument to FreeAndNil must be a TObject, or descendant thereof).
|