What is the meaning of nil owner in component constructor
Asked Answered
U

2

3

I was looking at this question and I'm wondering now, what is the meaning of nil as the owner in component constructor.

SomeComponent := TSomeComponent.Create(nil);

I know, that I should free it by myself when using this constructor, but is that the only reason to pass the owner at creation ? And what happens, when I forget to free it and close my application - does it mean that this object remains in memory as a garbage ?

Thanks a lot :)

Ursulina answered 24/3, 2011 at 13:54 Comment(0)
A
15

It means that you're responsible for freeing it yourself.

If you drop a component on a form, it's constructed with the form as the owner. This means that when the form is free'd, it will free all of the components it owns. The same applies if you pass a different owner (for instance, creating a TButton at runtime and making a TPanel it's owner); when the owner is being destroyed, it frees all of the components it owns in the process.

Using nil as the owner means that you're creating it manually in code, and you'll accept the responsibility to free it yourself. If you forget and your application closes, it's memory is released back to the operating system. However, if your application runs for a long time after you forget, you have a chunk of memory that's in use that shouldn't be.

Amoral answered 24/3, 2011 at 13:59 Comment(0)
I
1

You should read this article. It discusses how the VCL is designed to handle this ownership paradigm.

The article also gives examples of why it is important to not free components that are created with an owner as well.

Interleaf answered 24/3, 2011 at 14:30 Comment(1)
It might be "important to not free components that are created with an owner", but that can result in falling foul of bugs, e.g. QC#88776.Staple

© 2022 - 2024 — McMap. All rights reserved.