What is the correct way to dynamically create/release runtime forms?

user741875 picture user741875 · Jun 10, 2011 · Viewed 23.2k times · Source

I always try to create my Applications with memory usage in mind, if you dont need it then don't create it is the way I look at it.

Anyway, take the following as an example:

Form2:= TForm2.Create(nil);
try
  Form2.ShowModal;
finally
  Form2.FreeOnRelease;
end;

I actually think Form2.Destroy is probably the better option, which brings me to my question..

What is the difference between calling:

Form2.Destroy;
Form2.Free;
Form2.FreeOnRelease;

They all do the same or similar job, unless I am missing something.

And also when should any of the above be used? Obviously when freeing an Object I understand that, but in some situations is Destroy better suited than Free for example?

Answer

Cosmin Prund picture Cosmin Prund · Jun 10, 2011

Form2:= TForm2.Create(nil);

This is a code-smell, because Form2 is probably the global, IDE-generated variable that would normally hold an IDE-created TForm2. You most likely want to use a local variable, and one with a better name. This is not necessary an error, just a code-smell.

Form2.Destroy vs Form2.Free

Use Form2.Free, because it calls Destroy anyway. You can CTRL+Click on the name (Free) to see it's implementation. Essentially Free calls Destroy if Self is not nil.

Form2.FreeOnRelease

As the documentation says, "It should not be necessary to call FreeOnRelease directly."