3

私は本当に混乱しています。

// 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が表示されます。実行する割り当ての数に関係なく、値は変更されません。なぜだめですか?

4

2 に答える 2

16

Refcountは、オブジェクト変数ではなく、インターフェイス変数に割り当てる場合にのみ変更されます。

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; 
于 2010-10-13T03:32:28.520 に答える
3

クラス型変数に割り当てる場合、コンパイラは参照カウントコードを追加しません。refcountが1に設定されることはなく、2に設定されることもありませんでした。

の代わりにc1c2 を宣言すると、期待される動作が表示されます。IInterfaceTTestClass

于 2010-10-13T03:30:36.903 に答える