本文介绍了如何在Delphi中安全地创建和释放多个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您应该如何安全地创建和释放多个对象?
How should you safely create and free multiple objects?
基本上,这种事情是:
newOrderSource := TWebNewOrderSource.Create();
twData := TTWData.Create();
webData := TWebData.Create();
try
//do stuff
finally
newOrderSource.Free();
twData.Free();
webData.Free();
end;
在这种情况下,第二个和第三个create命令并不安全,因为它们与数据库一起使用。我应该只将所有Create放在try块中,然后在我免费调用它们之前检查它们是否已分配吗?
In this case, the second and third create commands aren't safe, as they work with a database. Should I just put all the Creates in the try block and check if they are assigned before I call free on them?
推荐答案
您如果首先给变量赋nil,就可以用一个try块来做到这一点,
You can do this with one try block if you assign nil to the variables first like,
newOrderSource := nil;
twData := nil;
webData := nil;
try
newOrderSource := TWebNewOrderSource.Create();
twData := TTWData.Create();
webData := TWebData.Create();
//do stuff
finally
webData.Free();
twData.Free();
newOrderSource.Free();
end;
之所以有效,是因为 Free()
检查自我
为 nil
。
This works because Free()
checks Self
for nil
.
这篇关于如何在Delphi中安全地创建和释放多个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!