对象Pascal:是否必须释放所有对象(类)? [英] Object Pascal: Must all objects (classes) be freed?

查看:110
本文介绍了对象Pascal:是否必须释放所有对象(类)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以扔掉class es而不释放它们吗,还是我的软件会开始喷出泄漏?

Can I throw around classes without freeing them, or will my software start spouting leaks?

例如,我可以这样做

Engine := TEngine.Create(TV);

然后摆脱引用,没有任何问题,还是必须先调用其Free方法?

Then get rid of the reference without any problems, or must I call its Free method first?

还是有一个返回TSomething并且不必稍后释放其引用的函数?

Or have a function that returns a TSomething and not having to free its reference later on?

推荐答案

一般规则是,如果创建它,则应释放它.最好的方法是尝试.最后,如果要在代码中创建它:

The general rule is that if you create it, you should free it. The best way is in a try..finally if you're creating it in code:

var
  Engine: TEngine;
begin
  Engine := TEngine.Create(TV);
  try
    // Do stuff with Engine
  finally
    Engine.Free;
  end;
end;

例外情况是,如果您有一个对象,该对象接受所有者作为参数(例如TEdit之类的可视控件或TComponent之类的非可视后代).如果您分配所有者,则将在所有者释放后将其释放. (如果您在没有所有者的情况下创建它,则仍然必须自己释放它.)

The exception to this is if you have an object that accepts an owner as a parameter (such as a visual control like TEdit or a non-visual descendant of TComponent). If you assign the owner, it will free it when the owner is freed. (If you create it without an owner, you still have to free it yourself.)

procedure TForm1.FormCreate(Sender: TObject);
var
  EditA, EditB: TEdit;
begin
  EditA := TEdit.Create(Self);  // You're passing the form as owner; don't free
  EditB := TEdit.Create(nil);   // Creating without an owner; you free.
end;

如果该类是另一个对象的成员(字段),则在包含对象的constructor中创建它,并在其destructor中释放它:

If the class is a member (field) of another object, you create it in the containing objects constructor and free it in its destructor:

type
  TOuterClass = class(TObject)
  private
    FEngine: TEngine;
  public
    constructor Create;
    destructor Destroy; override;
  end;

implementation

constructor TOuterClass.Create;
begin
  inherited;
  FEngine := TEngine.Create(TV);
end;

destructor TOuterClass.Destroy;
begin
  FEngine.Free;
  inherited;
end;

这篇关于对象Pascal:是否必须释放所有对象(类)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆