在我们现有的代码中,我们有一堆这样的表单,其中使用MainForm作为所有者(而不是nil)创建表单,但我们明确地释放它.
function SomeFunc(): Boolean; var form: TMyForm; // subclasses TForm begin with TMyForm.Create(Application.MainForm) do try ShowModal; Exit(True); finally Free; end end;
这会导致任何形式的错误或崩溃,还是安全的?
我似乎无法通过阅读文档来解决这个问题:
http://docwiki.embarcadero.com/Libraries/Berlin/en/System.Classes.TComponent.Owner
http://docwiki.embarcadero.com/Libraries/Berlin/en/System.Classes.TComponent.Create
解决方法
查看源代码,您可以自己回答这个问题!
TForm从TComponent深入继承,如果我们看一下TComponent的析构函数,我们看到这个(至少在DelphiXE7中):
destructor TComponent.Destroy; begin Destroying; RemoveFreeNotifications; DestroyComponents; if FOwner <> nil then FOwner.RemoveComponent(Self); FObservers.Free; inherited Destroy; end;
这里有两条重要的线:
> DestroyComponents
这将在销毁所有者本身之前销毁所有拥有的组件.
>如果FOwner<> nil然后FOwner.RemoveComponent(Self);
这通知所有者他拥有的对象不再存在,并且必须从所有者组件列表中删除它.
所以在你的情况下,Application.MainForm将拥有你的TMyForm实例,但是在销毁时它将从主表单组件列表中消失.
总而言之,您的代码非常好,不会崩溃.但为了清楚地表明您正在控制组件的生命周期,您应该在构造函数中将nil作为所有者传递.正如Sertac Akyuz在评论中已提到的,你将避免调用FOwner.RemoveComponent(Self);这将节省一些CPU周期……