Using Try and Finally to Help Prevent Memory Leaks During Dynamic Object Creation in Delphi
(Page 1 of 4 )
Using components in Delphi is child's play as long as your logic is sound. All you need to do is drop components on the form and Delphi takes care of dirtier things like allocating and de-allocating memory for the object. There are times when it doesn't handle memory allocation, however, depending on your needs. This article will explain how to handle those times.
For example, there may arise a need when you would want to create and destroy an object at runtime. It is during these times that you need to be extra careful about how you handle memory allocation and de-allocation. But why would you want to create components at runtime when you can simply drop components during design time and let Delphi handle the creation and destruction of the components?
The answer is you don't have to do it when you are working with a couple of buttons and a label component that are used throughout the lifetime of the application. In a more complex (and highly likely) situation, however, you are going to need much more than these three components. There is a great probability that some of the components you would want to use would be non-visual components like database components which are not visible at runtime.
Further, these components may be employed locally within a block only and not used throughout the program, unlike most data-aware components. Dropping components during design-time in these situations results in their instantiation when the application starts and are destroyed when the application terminates (assuming that the application has a Form which is the Owner of the object and which is created when the application initializes). While it may sound convenient, the big drawback of this approach is the fact that we are improperly using system resources by allocating them to objects that are not needed all the time. Creating these objects at runtime frees up resources and prevents any degradation of performance.
Another scenario where you would like to create components during runtime is when you don't know the number of components or the type of component to be created, or both. For instance, your program might require the user to specify how many buttons should be created. These two may not be the only situations for which you would want to create components at runtime; you may want to do it just for fun, but in any case it should always be borne in mind that the components need to be explicitly freed after they have been used.
Next: Creating and Destroying Components in Delphi >>
More Delphi-Kylix Articles
More By Danish Ahmed