Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

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

I'm really confused.

// 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;

It should show 1, but it shows 0. No matter how many assignments we'll perform, the value would not change! Why not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...