What is the meaning of nil owner in component constructor

为君一笑 提交于 2019-12-18 08:57:00

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5420260/what-is-the-meaning-of-nil-owner-in-component-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!