delphi - 为什么我的 Delphi 对象没有调用 _AddRef 和 _Release?

标签 delphi interface reference-counting

我真的很困惑。

// 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。无论我们将执行多少次分配,值都不会改变!为什么不?

最佳答案

仅当您分配给接口(interface)变量而不是对象变量时,才会修改 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; 

关于delphi - 为什么我的 Delphi 对象没有调用 _AddRef 和 _Release?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3920470/

相关文章:

multithreading - 用于提高性能的线程

c# - 如何实现内部接口(interface)的成员

java - 当接口(interface)完全抽象时,为什么说接口(interface)支持多重继承?

c++ - 下面的代码会不会出现赛车的情况?

delphi - 无法从 StringStream 获取字符串

windows - Windows 8 特定多媒体键的虚拟键代码是什么?

java - 子类是否获取父类(super class)实现的接口(interface)?

Objective-C ARC 构造函数应该设置实例变量还是属性?

c++ - 为什么 shared_ptr 需要保存 weak_ptr 的引用计数?

delphi - 将<T>类型的值转换为Variant,可能吗?