Mega Code Archive

 
Categories / Delphi / Ide Indy
 

The role of the AOwner parameter in the Create constructor of Delphi components

Title: The role of the "AOwner" parameter in the Create constructor of Delphi components Whenever memory is allocated for an object, it must eventually be freed (or you'll produce a memory leak). But with components, there is often little mention of the need to do this. Delphi must be destroying the objects, but how does it know when we’re through with them? Here's a hint. TComponent declares the Create constructor as follows: constructor Create(AOwner: TComponent) ; virtual; The answer is in the "AOwner" parameter to the Create constructor. The Create constructor is virtual (and is a class method). Every component that resides on the palette inherits this constructor. Inside the constructor, Delphi creates the component, and if an owner (hint: Owner vs. Parent) is specified (if AOwner is not nil), Delphi adds the newly-created component to the Owner's internal owned component list. This internal list is consulted by Delphi for three important events that can affect an owner (e.g., any TComponent descendant): A new component is created and added to the internal component list. When this happens, every component on the internal list is notified by calling the virtual method, Notification, passing a reference to the new component and specifying opInsert as the Operation. The Notification method is critical to support component linking. A new component is destroyed and removed from the internal component list. When this happens, every component on the internal list is notified by calling the virtual method, Notification, passing a reference to the new component and specifying opRemove as the Operation. The owner component is destroyed. When this happens, every owned component on the internal list is destroyed (and any components owned by these components are also recursively destroyed). That’s why you don’t need to explicitly destroy components that are owned, and this is part of what makes programming in Delphi so easy. The role of the AOwner parameter is even more important when you are creating Delphi components at run-time. If you are creating forms dynamically the AOwner can be set to nil, Self or Application.