Search code examples
c++formsc++builderfiremonkeyc++builder-xe8

Managing memory with form creation in C++ Builder / Firemonkey


So far, in my application it has worked out that all additional forms that were created at runtime, should be modal. Thus, when creating a new form I use something similiar the following block of code:

void __fastcall ShowForm( TComponent * Owner )
{
    TForm1 * form = new TForm1( Owner );
    form->ShowModal();

    delete form;
}

With this approach, the form's memory is easily deleted after the user has closed it.

However, I am running into an issue when trying to figure out how to handle memory management for a non modal dialog. Obviously, I can't simply call delete at the end of the ShowForm method as the form would be deleted right after it was created. So I am left with something like this:

void __fastcall ShowForm( TComponent * Owner )
{
    TForm1 * form = new TForm1( Owner );
    form->Show();
}

Based on this documentation and a test application I have written, I know that the form pointer will be deleted once its owner has been closed. However, that still leaves me with the following scenario:

Lets say I have FormA with a button that creates and shows an instance of FormB using code just like the method above. I now click the button to create a FormB and then close FormB, three times. Until FormA is closed, the three instances of FormB remain in memory.

How do I manage memory for form creation such that the memory allocated for a form is deleted once that form is closed? Is there a standard best practice for this, or a built in feature I am missing?


Solution

  • Use the TForm::FormClose event, and set the Action parameter to caFree:

    void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
    {
      Action = TCloseAction::caFree;
    }
    

    The Form will then free itself when it is closed.