1. Technology

A warning on dynamically instantiating components


1 of 10

Dynamic Component Creation Gotcha (Don't Do This)
A warning on dynamically instantiating components

In the Dynamic Component Creation article we discussed the following code sample that demonstrated the wrong way to dynamically create and free a TComponent descendant that is only needed within a single method (created and freed in the same block of code).

In the article a warning was issued against dynamically creating components with valid owners and then explicitly freeing the new objects afterwards. The following is an example of this (the TTable class is used for this example, but the issues raised in this article concern the dynamic creation of any TComponent descendant).

Looking at the code, the "Free" statement will always be called as long as the TTable creation is successful, which means the Create class method returns without raising an exception. Because of this, the TTable component, no matter what, will be alive (instantiated, assigned, and valid) only within the try/finally code block above.

Unfortunately, this "redundant safety net" can introduce the following undesirable side-effects:

©2014 About.com. All rights reserved.