简体   繁体   English

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

[英]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! 它应该显示1,但它显示0.无论我们将执行多少分配,值都不会改变! Why not? 为什么不?

Refcount is only modified when you assign to an interface variable, not to an object variable. 只有在分配给接口变量而不是对象变量时,才会修改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; 

The compiler doesn't add in any ref-counting code if you assign it to a class type variable. 如果将其分配给类类型变量,编译器不会添加任何引用计数代码。 The refcount was never even set to 1, much less 2. refcount从未设置为1,更不用说2。

You'll see the expected behavior if you declare c1 and c2 as IInterface instead of TTestClass . 如果将c1c2声明为IInterface而不是TTestClass您将看到预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Delphi:为什么FreeAndNil *真的没有我的对象? - Delphi: why doesn't FreeAndNil *really* nil my object? Delphi:调用 Delete() 后 TObjectList 不会释放 object - Delphi: TObjectList won't free object after Delete() is called Delphi将我的对象编组为字符串泄漏,但是为什么呢? - Delphi Marshalling my object to string leaks, but why? 为什么我的光标没有变成Delphi中的FindDialog中的沙漏? - Why doesn't my cursor change to an Hourglass in my FindDialog in Delphi? 如何跟踪OLE自动化对象的_AddRef / _Release调用 - How to trace _AddRef / _Release calls for OLE Automation objects Delphi 7布尔方程不起作用 - Delphi 7 boolean equations aren't working 为什么FireDac ODBC驱动程序在Delphi 10.01 Berlin发行版下无法连接到Sybase 9? - Why FireDac ODBC driver won't connect to Sybase 9 on release mode from Delphi 10.01 Berlin? 为什么我的Delphi不接受私下声明中的任何内容? - Why won't my Delphi accept anything under a private declaration? 为什么快捷方式在我的 Delphi 程序中不起作用? - Why the shortcut doesn't work in my Delphi program? Delphi仍然保留在内存中并且不释放,为什么? - Delphi still keep on memory and do not release, why?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM