Newbie question about release, freeAndNil, etc



ok. I suspect this is a newbie question, hence the subject line. Be
nice to me :)

(I'm using Delphi 6, btw)

When you create a Form, Delphi gives you a global variable to use. We
actually use them, so in our code we have things like:

i.e., in a button click handler:
if not assigned(frmViewerOptions) then
frmViewerOptions := TFrmViewerOptions.create(application);
frmViewerOptions.showModal;

etc

What is the recommended way of freeing these forms? We have several
variations:

1)
frmViewerOptions.showModal;
//stuff
freeAndNil(frmViewerOptions);
----
2)
frmViewerOptions.showModal;
//stuff
frmViewOptions.release;
frmViewerOptions := nil;
----
3)
frmViewerOptions.showModal;
//stuff
frmViewOptions.release;
freeAndNil(frmViewerOptions);
----
4)
in the FormClose handler of the form (TFrmViewerOptions):
action := caFree;
frmViewerOptions := nil;
----
5)
in the FormClose handler of the form:
release;
frmViewerOptions := nil;

========

My question doesn't concern the use of global variables (I have a
instictive dislike of this way of doing things, fwiw), but the freeing
of the memory and nil-ling of the reference variable. The Delphi help
files don't seem to give much guidance on this.

Personally, I lean towards option #3 above, but I think a case can be
made for #4, but making the variable nil there seems wrong to me.

What about doing action := caFree in the FormClose handler, and then
assigning the nil in the calling method (after the showModal call)?


Hopefully, I've explained this clearly... :)

-Corinna

.


Quantcast