开发者

What is the meaning of nil owner in component constructor

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

SomeComponent := TSomeCo开发者_开发知识库mponent.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 :)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜