Is passing a NULL Owner argument for dynamically created TComponent derived class instances OK?

434 views Asked by At

I work with C++ RAD Studio and Builder 6 quite a bit and often create forms dynamically or create non-visual components dynamically when writing non-visual code. When designing forms, the Owner property of components dropped onto that form is automatically set so I have never worried about it. However, when creating anything derived from TComponent dynamically I always pass NULL as the Owner argument as I am always taking responsibilty for freeing the memory later.

Borland/Embarcadero documentation doesn't really cover what is required in the case of dynamically creating things (or maybe I have not been looking in the right places) and only seems to ever cover design time form based scenarios.

I would like to know if passing a NULL owner for dynamically created components is the right thing to do, or if it can lead to internal problems that will manifest themselves later. Code compiles and works ok but I wonder if it is causes or potentially causes any behind the scenes problems.

1

There are 1 answers

7
Lieven Keersmaekers On BEST ANSWER

It's certainly not a wrong thing to do.

Passing an owner, as you already hinted to, alleviates you from having to manage the lifetime of the object yourself. There are no hidden internal side-effects that require you to pass an owner.

FWIW: Creating/using and destroying ownerless components is not uncommon, we do it all the time.


Edit cudo's to Remy

While the components that ship with your installation are fine to use without an owner (beside some corner cases like TXMLDocument that act differently with an owner assigned) , there's always the possibility of a third party or home brew component that rely on the owner being assigned.