Dealing with circular strong references in Delphi

后端 未结 4 1141
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 16:57

I got two classes (in my example TObject1 and TObject2) which know each other via interfaces (IObject1, IObject2). As you probably know in Delphi this will lead to a memory

4条回答
  •  没有蜡笔的小新
    2021-01-18 17:38

    If you want to keep both objects alive or dead together, the surely they are one single object. OK, I get that both may be developed by different people, so then I would make them both members of one super-object that is reference counted, like this

    type
      TSuperobject = class( TInterfaceObject, IObject1, iObject2 )
      private
        fObject1 : TObject1;
        fObject2 : TObject2;
      public
        constructor Create;
        destructor Destroy;
        function GetObject2: IObject2;
        etc.
      end;
    
    etc.
    

    The details should be obvious. Any reference to object1 or object2 must reference the owning object( superobject.object1 etc.), so object1 and object2 themselves do not need to be reference counted - i.e. they can be regular objects, not interfaced objects, but it actually doesn't matter if they are reference counted because the owner will always add 1 to the reference count (in that case you may not need the destructor in the superobject). If you are leaving object1 and object2 as referenced objects make their refence to each other both weak.

提交回复
热议问题