【问题标题】:Why aren't _AddRef and _Release called on my Delphi object?为什么我的 Delphi 对象没有调用 _AddRef 和 _Release?
【发布时间】:2011-04-24 15:26:45
【问题描述】:

我真的很困惑。

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

{...}

// test procedure
procedure testMF();
var c1, c2 : TTestClass;
begin
    c1 := TTestClass.Create(); // create, addref
    c2 := c1; // addref

    c1 := nil; // refcount - 1

    MessageBox( 0, pchar( inttostr( c2.refcount)), '', 0); // just to see the value
end;

它应该显示 1,但它显示 0。无论我们将执行多少次分配,值都不会改变!为什么不呢?

【问题讨论】:

    标签: delphi interface reference-counting


    【解决方案1】:

    仅在分配给接口变量而不是对象变量时才会修改引用计数。

    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; 
    

    【讨论】:

    • 谢谢肯,确实如此...我错过了接口,这是我的史诗般的失败:(但是我在余生中都学会了这一点...
    【解决方案2】:

    如果您将其分配给类类型变量,编译器不会添加任何引用计数代码。引用计数从未设置为 1,更不用说 2。

    如果您将c1c2 声明为IInterface 而不是TTestClass,您将看到预期的行为。

    【讨论】:

    • 如果您将 c1 和 c2 声明为 IInterface 而不是 TTestClass,您将看到预期的行为 - 这就是我真正想要的,非常感谢!
    猜你喜欢
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 2012-01-30
    相关资源
    最近更新 更多