为什么我的Delphi对象上没有调用_AddRef和_Release? [英] Why aren't _AddRef and _Release called on my Delphi object?

查看:399
本文介绍了为什么我的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.无论我们将执行多少作业,价值不会改变!为什么不呢?

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

推荐答案

只有在分配给接口变量而不是对象变量时才会修改Refcount。

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; 

这篇关于为什么我的Delphi对象上没有调用_AddRef和_Release?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆