delphi - 在 Delphi 中 class(TInterfacedObject) 是否需要析构函数?
问题描述
Destroy()
我在这种从未被调用的情况下运行。
unit Unit2;
interface
type
// Interface
ITest = Interface(IInterface)
function IsTrue() : Boolean;
end;
TmyClass = class(TInterfacedObject, ITest)
public
// Interface implementation
function IsTrue() : Boolean;
constructor Create();
destructor Destroy(); override;
end;
implementation
constructor TmyClass.Create();
begin
inherited Create();
end;
destructor TmyClass.Destroy();
begin
inherited Destroy();
end;
published
// Property
property IsItTrue: Boolean read IsTrue;
end.
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, unit2;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
fMyClass: TmyClass;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
fMyClass.Free; // if refcount = 0 this works, if refcount <> 0 pointer error.
//or
fMyClass := Nil; // no error but Destroy wil not be executed
Close();
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
fMyClass := TMyClass.Create();
end;
end.
阅读这篇文章,只有一个构造函数,没有实现析构函数。
这有什么特别的原因吗?
我是否应该释放(如果需要)将myClass
通过实现一个finalization
部分来定义的所有其他对象?
解决方案
未调用析构函数的最可能原因是您没有将对象分配给接口变量。
procedure Test1;
var
vMyObj : TObject;
begin
vMyObj := myclass.Create;
end; <-Destructor NOT called here
procedure Test2;
var
vMyIntf : IInterface;
begin
vMyIntf := myclass.Create;
end; <-Destructor IS called here.
如果是这种情况,我邀请您阅读此答案以获取更多信息。
推荐阅读
- asp.net-core - 使用 Saml2 和 Okta 作为服务提供者的 Asp.Net Core 3 中的用户身份验证
- azure - 在 Azure Devops 的拉取请求中显示接受标准
- spring-boot - Cassandra 读取查询返回空结果使用 springframework 数据 cassandra
- javascript - 我应该使用队列系统来处理多租户系统中的 PDF 文本识别吗?
- vb.net - 加载一个包含 15 个数字的 .txt 文件,显示它们并删除重复的 VB.net
- nix - 为什么 Nix lambdas 和 ? 操作员是这样交互的吗?
- javascript - 如何在两个javascript函数之间实现一个promise?
- google-ads-api - 连接媒体文件和广告
- angular - ag-grid tooltip tooltipField 不显示所有字符,包括特殊字符
- ios - IOS上的Flutter Firebase推送通知,收到消息但从未推送到系统托盘