为什么不在我的Delphi对象上调用_AddRef和_Release?
问题描述:
我真的很困惑。为什么不在我的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.无论我们要执行多少任务,值都不会改变!为什么不?
答
只有在分配给接口变量而不是对象变量时才会修改引用计数。
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;
答
如果将其分配给类型变量,编译器不会添加任何重新计数代码。引用计数是从来没有设置为1,更不用说2.
你会看到预期的行为,如果你声明c1
和c2
为IInterface
,而不是TTestClass
。
+0
如果您将c1和c2声明为IInterface而不是TTestClass,那么您会看到预期的行为 - 这正是我真正想要的,巨大的THX! – Focker 2010-10-13 03:35:09
thx肯,它的确如此......我错过了接口的使用权,这是我的史诗般的失败:(但是我已经学会了这一切,我的余生... – Focker 2010-10-13 03:38:38