Delphi接口引用计数

15
今天我在测试时遇到了一个奇怪的情况。
我有许多接口和对象。代码看起来像这样:
IInterfaceZ = interface(IInterface)
['{DA003999-ADA2-47ED-A1E0-2572A00B6D75}']
  procedure DoSomething;
end;

IInterfaceY = interface(IInterface)
  ['{55BF8A92-FCE4-447D-B58B-26CD9B344EA7}']
  procedure DoNothing;
end;

TObjectB = class(TInterfacedObject, IInterfaceZ)
  procedure DoSomething;
end;

TObjectC = class(TInterfacedObject, IInterfaceY)
public
  FTest: string;
  procedure DoNothing;
end;

TObjectA = class(TInterfacedObject, IInterfaceZ, IInterfaceY)
private
  FInterfaceB: IInterfaceZ;
  FObjectC: TObjectC;
  function GetBB: IInterfaceZ;
public
  procedure AfterConstruction; override;
  procedure BeforeDestruction; override;
  property BB: IInterfaceZ read GetBB implements IInterfaceZ;
  property CC: TObjectC read FObjectC implements IInterfaceY;
end;

procedure TObjectB.DoSomething;
begin
  Sleep(1000);
end;

procedure TObjectA.AfterConstruction;
begin
  inherited;
  FInterfaceB := TObjectB.Create;
  FObjectC := TObjectC.Create;
  FObjectC.FTest := 'Testing';
end;

procedure TObjectA.BeforeDestruction;
begin
  FreeAndNil(FObjectC);
  FInterfaceB := nil;
  inherited;
end;

function TObjectA.GetBB: IInterfaceZ;
begin
  Result := FInterfaceB;
end;

procedure TObjectC.DoNothing;
begin
  ShowMessage(FTest);
end;

现在,如果我像这样访问各种实现,我会得到以下结果:
procedure TestInterfaces;
var
  AA: TObjectA;
  YY: IInterfaceY;
  ZZ: IInterfaceZ;
  NewYY: IInterfaceY;
begin
  AA := TObjectA.Create;
  // Make sure that the Supports doesn't kill the object. 
  // This line of code is necessary in XE2 but not in XE4
  AA._AddRef;

  // This will add one to the refcount for AA despite the fact
  // that AA has delegated the implementation of IInterfaceY to
  // to FObjectC.
  Supports(AA, IInterfaceY, YY);
  YY.DoNothing;

  // This will add one to the refcount for FInterfaceB.
  // This is also allowing a supports from a delegated interface
  // to another delegated interface.
  Supports(YY, IInterfaceZ, ZZ);
  ZZ.DoSomething;

  // This will fail because the underlying object is actually
  // the object referenced by FInterfaceB.
  Supports(ZZ, IInterfaceY, NewYY);
  NewYY.DoNothing;
end;

第一个Supports调用使用implements中的变量返回YY,实际上是TObjectA的引用。我的AA变量有引用计数。因为底层的引用计数对象是TObjectA,所以第二个supports使用接口在supports调用中可以工作并返回一个接口。底层对象实际上现在是TObjectB。FInterfaceB内部对象是被引用计数的对象。这部分内容是有意义的,因为GetBB实际上是FInterfaceB。最后一个Supports调用返回NewYY的空值,最后的调用失败了。
我的问题是,第一个Supports调用中对TObjectA的引用计数是设计上的吗?换句话说,当实现接口的属性返回一个对象而不是一个接口时,这是否意味着所有者对象将进行引用计数?我一直以为implements也会导致内部委托对象被引用计数,而不是主对象。
声明如下:
  property BB: IInterfaceZ read GetBB implements IInterfaceZ;

使用上述选项,FInterfaceB背后的内部对象是被引用计数的那个对象。
  property CC: TObjectC read FObjectC implements IInterfaceY;

使用以上第二种选项,被引用计数的是TObjectA而不是委托对象FObjectC。这是设计如此吗?
编辑:我在XE2中进行了测试,行为不同。第二个Supports语句对ZZ返回nil。XE4中的调试器告诉我YY是指(TObjectA as IInterfaceY)。而在XE2中,则告诉我它是(Pointer as IInterfaceY)。此外,在XE2中,第一个支持语句中的AA没有被引用计数,但内部的FObjectC被引用计数。
补充问题回答后的附加信息:
这有一个警告。你可以链接接口版本,但不能链接对象版本。这意味着像这样的东西将会起作用:
TObjectBase = class(TInterfacedObject, IMyInterface)
  …
end;

TObjectA = class(TInterfacedObject, IMyInterface)
  FMyInterfaceBase: IMyInterface;
  property MyDelegate: IMyInterface read GetMyInterface implements IMyInterface;
end;

function TObjectA.GetMyInterface: IMyInterface;
begin
  result := FMyInterfaceBase;
end;

TObjectB = class(TInterfacedObject, IMyInterface)
  FMyInterfaceA: IMyInterface;
  function GetMyInterface2: IMyInterface;
  property MyDelegate2: IMyInterface read GetMyInterface2 implements IMyInterface;
end;

function TObjectB.GetMyInterface2: IMyInterface;
begin
  result := FMyInterfaceA;
end;

但是使用对象版本会出现编译错误,提示TObjectB没有实现接口的方法。

TObjectBase = class(TInterfacedObject, IMyInterface)
  …
end;

TObjectA = class(TInterfacedObject, IMyInterface)
  FMyObjectBase: TMyObjectBase;
  property MyDelegate: TMyObjectBase read FMyObjectBase implements IMyInterface;
end;

TObjectB = class(TInterfacedObject, IMyInterface)
  FMyObjectA: TObjectA;
  property MyDelegate2: TObjectA read FMyObjectA implements IMyInterface;
end;

因此,如果您想开始链接委托,那么您需要遵守接口或另找方法解决。


您只有对TObjectA的弱引用,因此您将失去AA以及其余内容。 - Sir Rufo
@SirRufo 我明白这一点,那只是一个例子。我更关心的是引用计数是如何完成的。基本上是哪个对象被引用计数。 - Graymatter
只需覆盖 _AddRef/_Release 方法调用并记录它们以及您的主过程,然后您就可以看到它。 - Jeroen Wiert Pluimers
1
@JeroenWiertPluimers 我可以看到哪些对象正在被引用计数。我想确认这种行为是设计上的,而不是我看到的错误。在类型为IInterfaceZ的属性中,内部对象是被引用计数的。在类型为TObjectC的属性中,所有者对象正在被引用计数。 - Graymatter
这是一个非常好的问题,给你点赞! - David Heffernan
2个回答

17

简而言之 这是设计上的问题 - 只是XE2和XE3之间的设计有所不同。

XE3及以后版本

委托给接口类型属性和委托给类类型属性之间存在很大差异。确实,documentation明确指出了这两种委托变体的不同部分。

从您的角度来看,差异如下:

  • TObjectA通过委托到类类型属性CC来实现IInterfaceY时,实现对象是TObjectA的实例。
  • TObjectA通过委托到接口类型属性BB来实现IInterfaceZ时,实现对象是实现FInterfaceB的对象。

在这一切中需要意识到的关键是,当您委托给类类型属性时,被委托的类不需要实现任何接口。所以它不需要实现IInterface接口,也不需要_AddRef_Release方法。

为了看到这一点,请修改您代码中TObjectC的定义如下:

TObjectC = class
public
  procedure DoNothing;
end;

你会发现这段代码编译、运行并且表现与你的版本完全相同。事实上,这是将接口委托给类类型属性时理想的声明方式。这样做避免了混合使用接口和类类型变量时的生命周期问题。
因此,让我们来看看你对Supports的三个调用:
Supports(AA, IInterfaceY, YY);

这里实现对象是AA,因此AA的引用计数会增加。

Supports(YY, IInterfaceZ, ZZ);

在这里,实现对象是TObjectB的实例,因此它的引用计数会增加。
Supports(ZZ, IInterfaceY, NewYY);

在这里,ZZ是由TObjectB实例实现的接口,该实例未实现IInterfaceY。因此,Supports返回FalseNewYYnil

XE2及更早版本

XE2和XE3之间的设计变化与移动ARM编译器的引入相一致,并且有许多低级别的更改来支持ARC。显然,其中一些更改也适用于桌面编译器。

我发现的行为差异涉及将接口实现委托给类类型属性。特别是当所涉及的类类型支持IInterface时。在这种情况下,在XE2中,内部对象执行引用计数。这与XE3不同,后者通过外部对象执行引用计数。

请注意,对于不支持IInterface的类类型,所有版本都由外部对象执行引用计数。这是有道理的,因为内部对象无法执行它。

以下是我的示例代码,以演示差异:

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  Intf1 = interface
    ['{56FF4B9A-6296-4366-AF82-9901A5287BDC}']
    procedure Foo;
  end;

  Intf2 = interface
    ['{71B0431C-DB83-49F0-B084-0095C535AFC3}']
    procedure Bar;
  end;

  TInnerClass1 = class(TObject, Intf1)
    function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
    procedure Foo;
  end;

  TInnerClass2 = class
    procedure Bar;
  end;

  TOuterClass = class(TObject, Intf1, Intf2)
  private
    FInnerObj1: TInnerClass1;
    FInnerObj2: TInnerClass2;
  public
    constructor Create;
    function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
    function _AddRef: Integer; stdcall;
    function _Release: Integer; stdcall;
    property InnerObj1: TInnerClass1 read FInnerObj1 implements Intf1;
    property InnerObj2: TInnerClass2 read FInnerObj2 implements Intf2;
  end;

function TInnerClass1.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
  if GetInterface(IID, Obj) then
    Result := 0
  else
    Result := E_NOINTERFACE;
end;

function TInnerClass1._AddRef: Integer;
begin
  Writeln('TInnerClass1._AddRef');
  Result := -1;
end;

function TInnerClass1._Release: Integer;
begin
  Writeln('TInnerClass1._Release');
  Result := -1;
end;

procedure TInnerClass1.Foo;
begin
  Writeln('Foo');
end;

procedure TInnerClass2.Bar;
begin
  Writeln('Bar');
end;

constructor TOuterClass.Create;
begin
  inherited;
  FInnerObj1 := TInnerClass1.Create;
end;

function TOuterClass.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
  if GetInterface(IID, Obj) then
    Result := 0
  else
    Result := E_NOINTERFACE;
end;

function TOuterClass._AddRef: Integer;
begin
  Writeln('TOuterClass._AddRef');
  Result := -1;
end;

function TOuterClass._Release: Integer;
begin
  Writeln('TOuterClass._Release');
  Result := -1;
end;

var
  OuterObj: TOuterClass;
  I1: Intf1;
  I2: Intf2;

begin
  OuterObj := TOuterClass.Create;

  Supports(OuterObj, Intf1, I1);
  Supports(OuterObj, Intf2, I2);

  I1.Foo;
  I2.Bar;

  I1 := nil;
  I2 := nil;

  Readln;
end.

在XE2上的输出为:

TInnerClass1._AddRef
TOuterClass._AddRef
Foo
Bar
TInnerClass1._Release
TOuterClass._Release

XE3的输出是:

TOuterClass._AddRef
TOuterClass._AddRef
Foo
Bar
TOuterClass._Release
TOuterClass._Release

讨论

为什么设计会改变?我不能确定地回答这个问题,因为我不知道决策的过程。然而,在XE3中的行为对我来说感觉更好。如果你声明一个类类型的变量,你会希望它的生命周期像其他类类型的变量一样被管理。也就是说,在桌面编译器上通过显式调用析构函数,在移动编译器上通过ARC进行管理。

另一方面,XE2的行为感觉不一致。为什么一个属性被用于接口实现委托会改变它的生命周期管理方式呢?

所以,我的直觉告诉我,这是一个设计缺陷,最多只能算是在接口实现委托的原始实现中。这个设计缺陷导致了多年的混乱和生命周期管理问题。ARC的引入迫使Embarcadero重新审视了这个问题,并且他们改变了设计。我相信,ARC的引入需要进行设计更改,因为Embarcadero有一个不改变行为的记录,除非绝对必要。

以上段落显然是我自己的猜测,但这是我能提供的最好的答案!


+1,“...类类型属性...不需要实现任何接口”。很棒,我在早上10:30之前就能学到新东西了。 - iamjoosy
@iamjoosy 是的,这对我来说也是新的! - David Heffernan
很好的答案。我同意XE3中的行为更好。它更加一致。它还给开发人员选择他们想要引用计数发生的位置。在XE2及之前,内部对象将是接口背后的基础对象(当它实现接口时)。这限制了在使用委托时在接口上使用Supports的使用。 - Graymatter
谢谢你的问题。像往常一样,我学到了很多东西,这次甚至可能比你还多!!;-) 因为你在隔离问题方面做得非常好。顺便说一句,这真是个好问题。我希望更多的人能像你这样清晰地提出问题。 - David Heffernan

3

您正在混合使用对象指针和接口指针,这总是一个灾难的配方。 TObjectA 没有增加内部对象的引用计数,以确保它们在其整个生命周期内保持活动状态,TestInterfaces() 没有增加 AA 的引用计数,以确保它能在整个测试集中存活下来。对象指针不参与引用计数!您必须手动管理它,例如:

procedure TObjectA.AfterConstruction;
begin
  inherited;
  FObjectB := TObjectB.Create;
  FObjectB._AddRef;
  FObjectC := TObjectC.Create;
  FObjectC._AddRef;
  FObjectC.FTest := 'Testing';
end;

procedure TObjectA.BeforeDestruction;
begin
  FObjectC._Release;
  FObjectB._Release;
  inherited;
end;

AA := TObjectA.Create;
AA._AddRef;

不用说,手动引用计数削弱了接口的使用。

在处理接口时,您需要选择:

  1. 完全禁用引用计数以避免过早销毁。例如:TComponent就是这样做的。

  2. 仅使用接口指针进行所有操作,永远不要使用对象指针。这可确保整个系统中的正确引用计数。通常这是优选的解决方案。


这只是一小段测试代码。我没有任何表现出来的错误或其他问题。我更关心接口所附加的基础对象以及在两种情况下引用计数的对象是哪个。我理解引用计数的问题。如果我查看您的AfterConstruction方法并参考我的原始示例,就不需要在FObjectC上执行_AddRef,因为它从未被引用计数。这就是我的问题所在。在我添加的代码中,FObjectB正在被引用计数,但FObjectC没有。问题已经整理过了。 - Graymatter
XE2在这段代码中表现出与XE4不同的行为。我已经更新了问题以显示差异。 - Graymatter
@Remy 尽管你所说的都是正确的,但我认为你并没有真正理解这个问题。 - David Heffernan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接