问题描述
我有两个单位unitA和unitB。TFU在unitB中声明。
是否可以安全地调用B.Free完成unitA?
如何依赖于在dpr中unitA和unitB的顺序?
在执行unitA定稿时,我可以确定unitB是否存在?
unit unitB;
接口
type
TFoo = class
// code ...
end;
// code ....
end;
unit unitA;
//代码..
实现
使用
unitB;
var
A:TStringList;
B:UnitB.TFoo;
初始化
A:= TStringList.Create;
B:= UnitB.TFoo.Create;
finalization
A.Free;
B.Free; //可以安全地打电话吗?
结束。
是的,你应该很好,因为B被创建单元A.规则是根据DPR中的顺序调用初始化部分,除非其中一个单元引用另一个单元。在这种情况下,首先初始化初始化单元。完成的方式是相反的顺序。
在你的情况下,B单元没有一个初始化部分,所以这是一个模糊点。然而,当执行Unit A初始化部分时,它将使用Unit B中的TFoo定义。
关于初始化和定稿部分的另一个警告词 - 它们发生在全局之外异常处理程序。发生的任何异常都会终止应用程序。所以跟踪和调试这些例外可能是一个很大的程序的痛苦。您可以考虑在其中使用自己的异常日志记录,以确保。
I have two units unitA and unitB.Class TFoo is declared in unitB.
Is it allways safe to call B.Free in finalization of unitA?
How does it depend on in which order unitA and unitB are in dpr?
Can I be sure that unitB exists when unitA finalization is executed?
unit unitB;
interface
type
TFoo = class
// code...
end;
// code....
end;
unit unitA;
// code..
implementation
uses
unitB;
var
A: TStringList;
B: UnitB.TFoo;
initialization
A:= TStringList.Create;
B:= UnitB.TFoo.Create;
finalization
A.Free;
B.Free; // Is it safe to call?
end.
Yes, you should be fine since B is created in Unit A. The rule is that the Initialization sections are called based on the order they are in the DPR, unless one of the units references another unit. In that case, the referenced unit is initialized first. Finalization is in the reverse order.
In your case Unit B does not have an initialization section, so it is a moot point. It will however use the TFoo definition in Unit B when the Unit A initialization section is executed.
Another word of warning about Initialization and Finalization sections - they happen outside of the global exception handler. Any exception that occurs there just terminates the application. So tracking down and debugging those exceptions can be a pain in large programs. You might consider using your own exception logging in there, just to be sure.
这篇关于德尔福和一个单位完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!