Delphi中对象释放的问题

写前台程序的时候经常遇到自己创建对象的情况,我们知道delphi没有类似Java的内存回收技术,
所以要手动释放自己创建的对象。
  大部分对象创建的时候,在create构造函数中都有一个AOwner参数,该参数用来指定对象的owner,
先看一下delphi帮助中对owner属性的解释:
Delphi has a built-in memory-management mechanism that allows one component to assume
responsibility for freeing another. The former component is said to own the latter. The
memory for an owned component is automatically freed when its owner's memory is freed.
The owner of a component梩he value of its Owner property梚s determined by a parameter
passed to the constructor when the component is created. By default, a form owns all
components on it and is in turn owned by the application. Thus, when the application
shuts down, the memory for all forms and the components on them is freed.

Ownership applies only to TComponent and its descendants. If you create, for example,
a TStringList or TCollection object (even if it is associated with a form), you are
responsible for freeing the object.

...

Use Owner to find the owner of a component. When one component owns another, the memory
 for the owned component is freed when its owner's memory is freed. This means that when
 a form is destroyed, all the components on the form are also destroyed.

By default, a form owns all components that are on it. In turn, the form is owned by the
application. Thus when the application shuts down and its memory is freed, the memory for
all forms (and all their owned components) is also freed.

The owner of a component is determined by the parameter passed to the constructor when
the component is created. For components created in the form designer, the form is
automatically assigned as the owner.
  这段英文的意思大概如下:当一个对象具有owner时,它的owner负责它的内存释放。事实上TComponent
类内部有一个descendants的列表,当它自己被释放时,它会检查并释放所有的descendants。也就是说,
当你为对象指定了正确的owner属性,它的owner会负责对象的释放,你不必自己释放它的。
  可以写个很简单的程序进行验证:创建一个form,指定其owner为某个button,然后free这个button,你
会看到button和form都不见了。
  当然,这个规则只对从TComponent继承的对象适用。对于TStringList等不是从TComponent继承的类,该
类型的对象必须手动进行释放了。在这里有一个误区,就是free和nil的区别,free是释放对象的内存,nil
是将指针变量的引用指为空,即不引用任何东西。如果声明的变量类型为基本类型,比如integer,char等,
该变量在函数执行结束时会被自动释放;而如果变量类型为对象,则函数结束时只释放该变量本身,而不会
释放变量所指向的对象。对象类型的变量本身是个指针,包含对实际对象的引用。
  所以,当再碰到Create对象时,如果要指定AOwner参数,可要注意了,特别是将该参数赋为nil时,一定
要记得自己释放。不过,对大部分对象的创建可以指定AOwner参数为self,最差的情况可以添为application。
application对象在应用程序结束的时候会被释放。
  对于TStringList这样没有AOwner参数的类型变量,似乎没有捷径可走,只能自己手动释放了。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值