Delphi Interface Reference Counting

后端 未结 2 641
忘掉有多难
忘掉有多难 2021-02-04 07:00

I ran into a strange situation while testing something today.

I have a number of interfaces and objects. The code looks like this:

IInterfaceZ = interfac         


        
2条回答
  •  一向
    一向 (楼主)
    2021-02-04 07:43

    You are mixing object pointers and interface pointers, which is always a recipe for disaster. TObjectA is not incrementing the reference count of its inner objects to ensure they stay alive for its entire lifetime, and TestInterfaces() is not incrementing the reference count of AA to ensure it survives through the entire set of tests. Object pointers DO NOT participate in reference counting! You have to manage it manually, eg:

    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;
    

    Needless to say, manual reference counting undermines the use of interfaces.

    When dealing with interfaces, you need to either:

    1. Disable reference counting completely to avoid premature destructions. TComponent, for instance, does exactly that.

    2. Do EVERYTHING using interface pointers, NEVER with object pointers. This ensures proper reference counting across the board. This is generally the preferred solution.

提交回复
热议问题