组件构造函数中的 nil Owner 是什么意思

发布于 2024-10-26 01:51:28 字数 338 浏览 7 评论 0原文

我正在查看这个问题,我现在我想知道,nil 作为组件构造函数中的所有者是什么意思。

SomeComponent := TSomeComponent.Create(nil);

我知道,在使用此构造函数时我应该自己释放它,但这是在创建时传递所有者的唯一原因吗?当我忘记释放它并关闭我的应用程序时会发生什么 - 这是否意味着该对象作为垃圾保留在内存中?

多谢 :)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谜兔 2024-11-02 01:51:28

这意味着您有责任自行释放它。

如果将组件拖放到表单上,则会以该表单作为所有者来构造该组件。这意味着当表单被释放时,它将释放它拥有的所有组件。如果您传递不同的所有者(例如,在运行时创建 TButton 并使 TPanel 成为其所有者),则同样适用;当所有者被销毁时,它会释放在此过程中拥有的所有组件。

使用 nil 作为所有者意味着您在代码中手动创建它,并且您将承担自行释放它的责任。如果您忘记了并且您的应用程序关闭,它的内存将被释放回操作系统。但是,如果您的应用程序在您忘记后运行了很长时间,则您有一大块不应该使用的内存。

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.

久隐师 2024-11-02 01:51:28

您应该阅读这篇文章。它讨论了如何设计 VCL 来处理这种所有权范例。

本文还举例说明了为什么不释放由所有者创建的组件很重要。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文