[英]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
. 如果将
c1
和c2
声明为IInterface
而不是TTestClass
您将看到预期的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.