2010-10-13 42 views
2

我真的很困惑。爲什麼不在我的Delphi對象上調用_AddRef和_Release?

// 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.無論我們要執行多少任務,值都不會改變!爲什麼不?

回答

14

只有在分配給接口變量而不是對象變量時纔會修改引用計數。

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

thx肯,它的確如此......我錯過了接口的使用權,這是我的史詩般的失敗:(但是我已經學會了這一切,我的餘生... – Focker 2010-10-13 03:38:38

2

如果將其分配給類型變量,編譯器不會添加任何重新計數代碼。引用計數是從來沒有設置爲1,更不用說2.

你會看到預期的行爲,如果你聲明c1c2IInterface,而不是TTestClass

+0

如果您將c1和c2聲明爲IInterface而不是TTestClass,那麼您會看到預期的行爲 - 這正是我真正想要的,巨大的THX! – Focker 2010-10-13 03:35:09

相關問題