ITest = Interface
['{4979F659-C4BA-4F01-B09F-A4E7AA5022F1}']
procedure  Excute;
end;TTest = (TInterfaceObject, ITest)
private
  ID: integer;
public
  Excute;
end;var
 tt:TTest;
procedure Create;
begin
  if not assigned(tt) then  tt := TTest.Create;  //此时tt的引用计数怎么还是0?
  Insert(tt); //tt的引用计数变为1
  Remove(tt);  //tt的引用计数变为0,被释放了
  tt.Execute; //访问非法地址
end;procedure Insert(aItest: ITest);
begin
  FList.Insert(aItest);  //FList是TInterfaceList;
end;procedure Remove(aItest:ITest);
begin
  FList.Remove(aItest); 
end;为什么tt被创建以后引用计数还是0?

解决方案 »

  1.   

    TTest = (TInterfaceObject, ITest)
    private
      ID: integer;
      FRefCount: integer;
    public
      Function _AddRef : integer;Stdcall;
      Function _Release : integer;Virtual;StdCall;
      Excute;
    end;Function TTest._AddRef : Integer;
    begin
      Result:=InterLockedDerement(FRefCount)
    end;Function TTest._Release : integer;
    begin
      Result:=InterLockedDecrement(FRefCount);
    end;
      

  2.   

    才创建的时候,没有INTERFACE变量引用它,这时候当然引用计数为0.
    tt := TTest.Create;注意,这儿的tt类型是TTest而不是ITest!当调用时候,
     Insert(tt); //这时候才开始引用..
      

  3.   

    halfdream(哈欠) 正解既然你的类实现了接口,就不要调用类来创建实例,
      

  4.   

    _AddRef
    _Release或者自己实现IUnknown接口的这两个函数,
    直接 Result := -1;不实现计数也可以。