why aren't descendants of TInterfacedObject garbage collected?

后端 未结 3 563
臣服心动
臣服心动 2021-01-03 05:16

i have a class based on TInterfacedObject. i add it to TTreeNode\'s Data property.

TFacilityTreeItem=class(TInterfacedObject)
private
  m_guidItem:TGUID;
           


        
3条回答
  •  情歌与酒
    2021-01-03 06:06

    TInterfacedObject itself is not reference counted, only interfaces are. You can implement interfaces using TInterfacedObject which basically saves you the effort of implementing the reference counting methods yourself. Unfortunately it still will not work in your case: The compiler does not know that you are assigning interfaces to the TTreeNode.Data property since it is not declared as an interface but as a pointer. So all kinds of weird things will happen:

    MyInt := TFacilityTreeItem.Create; // ref count = 1
    // Node.Data := MyInt; // won't compile
    Node.Data := pointer(MyInt); // no interface assignment, ref count stays 1
    ...
    end; // ref count reaches 0, your object gets freed
    

    As soon as you try to access your object through the .Data property, you will get an access violation.

    So, don't bother with interfaces in this case, you could get it to work, but it will be much more effort than it is worth.

提交回复
热议问题