【发布时间】:2010-11-17 01:17:30
【问题描述】:
我最近偶然发现了一个由我编写的一些非常旧的代码引起的问题,该代码显然假设with 语句中使用的接口引用将在with-block 离开后立即释放 - 有点像隐式try-finally-block(如果我理解正确,类似于C#的using-statement)。
显然(在 Delphi 2009 中)这不是(不再是?)情况。有谁知道这是什么时候发生的?还是我的代码一开始就完全错误?
为了澄清,这里有一个简化的例子:
type
IMyIntf = interface;
TSomeObject = class(TInterfacedObject, IMyIntf)
protected
constructor Create; override; // creates some sort of context
destructor Destroy; override; // cleans up the context created in Create
public
class function GetMyIntf: IMyIntf; //a factory method, calling the constructor
end;
procedure TestIt;
begin
DoSomething;
with (TSomeObject.GetMyIntf) do
begin
DoStuff;
DoMoreStuff;
end; // <- expected: TSomeObject gets destroyed because its ref.count is decreased to 0
DoSomethingElse;
end; // <- this is where TSomeObject.Destroy actually gets called
每当有人开始旧的“with 是邪恶的”论点时,这始终是我想到的一个例子,它让我继续“是的,但是......”。好像我错了……谁能确认一下?
【问题讨论】:
标签: delphi interface delphi-2009 reference-counting with-statement