不久前我问了一个关于隐式接口变量的类似问题.
这个问题的来源是我的代码中的一个错误,因为我没有意识到编译器创建的隐式接口变量的存在.拥有它的过程完成后,该变量已完成.这反过来导致了由于变量的生命周期比我预期的更长的错误.
现在,我有一个简单的项目来说明编译器的一些有趣的行为:
program ImplicitInterfaceLocals;
{$APPTYPE CONSOLE}
uses
Classes;
function Create: IInterface;
begin
Result := TInterfacedObject.Create;
end;
procedure StoreToLocal;
var
I: IInterface;
begin
I := Create;
end;
procedure StoreViaPointerToLocal;
var
I: IInterface;
P: ^IInterface;
begin
P := @I;
P^ := Create;
end;
begin
StoreToLocal;
StoreViaPointerToLocal;
end.
Run Code Online (Sandbox Code Playgroud)
StoreToLocal编译就像你想象的那样.局部变量I(函数的结果)作为隐式var参数传递给Create.通过StoreToLocal一次通话即可获得整齐的结果IntfClear.没有惊喜.
但是,StoreViaPointerToLocal对待方式不同.编译器创建一个传递给它的隐式局部变量Create.当Create返回时,对分配P^进行.这使例程中有两个局部变量保存对接口的引用.StoreViaPointerToLocal两次调用结果的整理结果IntfClear.
编译后的代码StoreViaPointerToLocal是这样的:
ImplicitInterfaceLocals.dpr.24: begin
00435C50 55 …Run Code Online (Sandbox Code Playgroud)