Creating a Form Instance Using a Local Variable

From RAD Studio
Jump to: navigation, search

Go Up to Controlling When Forms Reside in Memory

A safer way to create a unique instance of a modal form is to use a local variable in the event handler as a reference to a new instance. If a local variable is used, it does not matter whether ResultsForm is auto-created or not. The code in the event handler makes no reference to the global form variable. For example:

procedure TMainForm.Button1Click(Sender: TObject);
void __fastcall TMainMForm::FirstButtonClick(TObject *Sender)
    TResultsForm *rf = new TResultsForm(this); // rf is local form instance
    delete rf; // form safely destroyed

Notice how the global instance of the form is never used in this version of the event handler.

Typically, applications use the global instances of forms. However, if you need a new instance of a modal form, and you use that form in a limited, discrete section of the application, such as a single function, a local instance is usually the safest and most efficient way of working with the form.

Of course, you cannot use local variables in event handlers for modeless forms because they must have global scope to ensure that the forms exist for as long as the form is in use. Show returns as soon as the form opens, so if you used a local variable, the local variable would go out of scope immediately.

See Also