Why aren't _AddRef and _Release called on my Delphi object?

前端 未结 2 1168
无人共我
无人共我 2020-12-20 02:14

I\'m really confused.

// initial class
type
    TTestClass = 
        class( TInterfacedObject)
        end;

{...}

// test procedure
procedure testMF();
va         


        
相关标签:
2条回答
  • 2020-12-20 03:12

    Refcount is only modified when you assign to an interface variable, not to an object variable.

    procedure testMF(); 
    var c1, c2 : TTestClass; 
        Intf1, Intf2 : IUnknown;
    begin 
        c1 := TTestClass.Create(); // create, does NOT addref
        c2 := c1; // does NOT addref 
    
        Intf1 := C2;  //Here it does addref
        Intf2 := C1;  //Here, it does AddRef again
    
        c1 := nil; // Does NOT refcount - 1 
        Intf2 := nil; //Does refcount -1
    
        MessageBox( 0, pchar( inttostr( c2.refcount)), '', 0); // just to see the value 
        //Now it DOES show Refcount = 1
    end; 
    
    0 讨论(0)
  • 2020-12-20 03:16

    The compiler doesn't add in any ref-counting code if you assign it to a class type variable. The refcount was never even set to 1, much less 2.

    You'll see the expected behavior if you declare c1 and c2 as IInterface instead of TTestClass.

    0 讨论(0)
提交回复
热议问题