Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically free classes/objects?

Tags:

delphi

What techniques exist to automatically free objects in delphi applications?

like image 306
Shannon Avatar asked Jan 06 '09 09:01

Shannon


2 Answers

Use interfaces instead of objects. They are reference counted and freed automatically when the reference count reaches 0.

like image 144
Glenner003 Avatar answered Oct 06 '22 00:10

Glenner003


I have written a function GC(obj: TObject) (for Garbage Collect) which takes an object and frees it when the execution leaves the current method. It's kind of like a one-line shorthand function for a Try Finally Free block.

Instead of:

procedure Test;
var AQuery: TQuery;
begin
  AQuery := TQuery.Create(nil);
  try
    ...
  finally
    FreeAndNil(AQuery);
  end;
end;

I just have:

procedure Test;
var AQuery: TQuery;
begin
  AQuery := TQuery.Create(nil);
  GC(AQuery);
  ...
end;

The GC function simply returns an object in the form of an interface.

function GC(obj: TObject): IGarbo;
begin
  Result := TGarbo.Create(obj);
end;

Because the TGarbo class descends from TInterfacedObject, when the TGarbo object goes out of scope it will automatically get freed. In the destructor of the TGarbo object, it also frees the object you passed to it in it's constructor (the object you passed in the GC function).

type
  IGarbo = interface
    ['{A6E17957-C233-4433-BCBD-3B53C0C2C596}']
    function Obj: TObject;
  end;

  TGarbo = class(TInterfacedObject, IGarbo)
  private
    FObj: TObject;
  public
    constructor Create(AObjectToGC: TObject);
    destructor Destroy; override;
    function Obj: TObject;
  end;

{ TGarbo }

constructor TGarbo.Create(AObjectToGC: TObject);
begin
  inherited Create;
  FObj := AObjectToGC;
end;

destructor TGarbo.Destroy;
begin
  if Assigned(FObj) then
    FreeAndNil(FObj);
  inherited;
end;

function TGarbo.Obj: TObject;
begin
  Result := FObj;
end;

Being stuck in the world of Delphi 7 with no sight of upgrading to a version of Delphi with built-in garbage collection in the near future, I'm addicted to using this short-hand method of easily freeing local temporary objects! :)

like image 44
CodeAndCats Avatar answered Oct 06 '22 00:10

CodeAndCats