Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
893 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...