【发布时间】:2015-09-15 12:20:50
【问题描述】:
我有两个相同代码的变体:
{$APPTYPE CONSOLE}
uses
System.SysUtils;
type
IMyObject1 = interface
['{4411181F-3531-4D30-AB18-A8326F8C2CD0}']
end;
IMyObject2 = interface
['{41C88E1A-0360-4AC3-B021-125880B23DE5}']
end;
TMyObject = class(TInterfacedObject, IMyObject1, IMyObject2)
public
destructor Destroy; override;
end;
destructor TMyObject.Destroy;
begin
Writeln('Destroy');
inherited;
end;
procedure Variant1;
function GetMyObject: IMyObject2;
var
Obj1: IMyObject1;
begin
Obj1 := TMyObject.Create;
try
Obj1.QueryInterface(IMyObject2, Result);
finally
Obj1 := nil;
end;
end;
var
Obj2: IMyObject2;
begin
Obj2 := GetMyObject;
try
finally
Obj2 := nil;
end;
Writeln('Variant1 end of proc');
end;
function GetMyObject: IMyObject2;
var
Obj1: IMyObject1;
begin
Obj1 := TMyObject.Create;
try
Obj1.QueryInterface(IMyObject2, Result);
finally
Obj1 := nil;
end;
end;
procedure Variant2;
var
Obj2: IMyObject2;
begin
Obj2 := GetMyObject;
try
finally
Obj2 := nil;
end;
Writeln('Variant2 end of proc');
end;
begin
Variant1;
Writeln('---');
Variant2;
Writeln('---');
Readln;
end.
输出
Variant1 过程结束 破坏 --- 破坏 Variant2 进程结束 ---为什么两个变体的行为不同?
【问题讨论】:
-
我希望你不介意我把问题改写一下,把代码变成一个MCVE
-
我确定您知道
GetMyObject的返回值是未定义的,会触发未定义的行为。 -
@Johan,返回值在 QueryInterface 调用中设置。在这种情况下为零。
-
@LURD 不是
nil,因为实现对象实现了IMyObject2。 -
@DavidHeffernan,我的错,我在之前的测试中从类定义中注释掉了 IMyObject2。
标签: delphi