接口"递归"和引用计数

Ste*_*eve 4 delphi oop interface

我的接口有一个小问题.这是伪代码:

type
  Interface1 = interface
  end;

  Interface2 = interface
  end;

  TParentClass = class(TInterfacedObject, Interface1)
  private
    fChild : Interface2;
  public
    procedure AddChild(aChild : Interface2);
  end;

  TChildClass = class(TInterfacedObject, Interface2)
  private
    fParent : Interface2;
  public
    constructor Create(aPArent : Interface1);
  end;
Run Code Online (Sandbox Code Playgroud)

任何人都可以看到这个缺陷吗?我需要孩子引用它的父级,但引用计数在这种情况下不起作用.如果我创建一个ParentClass实例,并添加一个子类,那么父类永远不会被释放.我明白为什么.我怎么绕圈呢?

Bar*_*lly 10

引用计数引用具有两个语义:它作为所有权的共享以及导航对象图的方式.

通常,您不需要在引用图的循环中的所有链接上同时使用这两种语义.也许只有父母自己的孩子,而不是相反?如果是这种情况,您可以通过将它们存储为指针来使子引用父弱链接,如下所示:

TChildClass = class(TInterfacedObject, Interface2)
private
  fParent : Pointer;
  function GetParent: Interface1;
public
  constructor Create(aPArent : Interface1);
  property Parent: Interface1 read GetParent;
end;

function TChildClass.GetParent: Interface1;
begin
  Result := Interface1(fParent);
end;

constructor TChildClass.Create(AParent: Interface1);
begin
  fParent := Pointer(AParent);
end;
Run Code Online (Sandbox Code Playgroud)

如果保证实例树的根在某处保持活动,这是安全的,即您不依赖于仅保留对树的分支的引用并且仍然能够导航它的整个部分.