- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我知道一个接口(interface)对象是引用计数的,所以不需要手动释放它。但是如果它有一个 TObject 继承的成员,我应该在析构函数中手动释放这个成员吗?
考虑以下代码:
program Project2;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes;
type
ITestInterface = interface(IInvokable)
['{A7BDD122-7DC6-4F23-93A2-B686571AB2C8}']
procedure TestMethod;
end;
TTestObj = class(TInterfacedObject, ITestInterface)
constructor Create;
destructor Destroy; override;
private
FData: TStrings;
public
procedure TestMethod;
end;
{ TTestObj }
constructor TTestObj.Create;
begin
FData := TStringList.Create;
end;
destructor TTestObj.Destroy;
begin
Writeln('Destroy'); // This line won't apear in the console ouput as the destructor won't be called.
FData.Free; // Who guarantees this member will be freed ?
inherited;
end;
procedure TTestObj.TestMethod;
begin
Writeln('TestMethod');
end;
{ Main }
procedure Main;
var
TestObj: TTestObj;
begin
TestObj := TTestObj.Create;
TestObj.TestMethod;
TestObj := nil; // TestObj should be freed at this moment ?
end;
begin
Writeln('Program start!');
Main;
Writeln('Program end.');
Readln;
end.
Program start!
TestMethod
Program end.
FData
没有被释放?
最佳答案
TTestObj
中的代码很好。您必须实现一个销毁 FData
的析构函数。正如你所做的那样。
问题出在其他地方。接口(interface)对象没有被销毁,因为您永远不会触发任何引用计数。您需要通过接口(interface)变量引用接口(interface)对象。代替
TestObj: TTestObj
TestObj: ITestInterface
TestObj
时添加引用。多变的。
TestObj := nil
TestObj
变量超出范围,引用计数将降至零,实现对象将被销毁。
关于delphi - 如何释放 TInterfacedObject 中的 TObject 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48983070/
我有一个基于 TInterfacedObject 的类。我将其添加到 TTreeNode 的 Data 属性中。 TFacilityTreeItem=class(TInterfacedObject)
我需要一个像TInterfacedObject这样的基类,但没有引用计数(所以是一种TNonRefCountedInterfacedObject)。 这实际上是我第n次需要这样的类(class),不知
According to the Delphi docs ,我可以使用 as 运算符将 TInterfacedObject 转换为接口(interface)。 但这对我不起作用。强制转换会产生编译错误
我正在基于:How can I allow a form to accept file dropping without handling Windows messages? 实现我的 IDropTa
我知道一个接口(interface)对象是引用计数的,所以不需要手动释放它。但是如果它有一个 TObject 继承的成员,我应该在析构函数中手动释放这个成员吗? 考虑以下代码: program Pro
我想实现IOleMessageFilter,如下所述: How to: Fix 'Application is Busy' and 'Call was Rejected By Callee' Erro
博客文章“Application Development with C++Builder and Delphi”说的是 Almost anything you write in Delphi can
我想知道 TInterfacedObject 派生类的实例何时被销毁以及谁调用析构函数。我写了一个ScopedLock类,它应该自动调用Release当实例超出范围时同步对象的方法。这是 C++ 中已
我需要一个类实现没有引用计数的接口(interface)。我做了以下事情: IMyInterface = interface(IInterface) ['{B84904DF-9E8A-
以下示例展示了如何开始针对接口(interface)进行编码: 来自 TMyObject = class function Add(a, b: integer): integer; end; 到
我是一名优秀的程序员,十分优秀!