Sie sind auf Seite 1von 2

Automatic Reference Counting in Delphi...

a tiny module to manage a 'garbage collector' in Delphi ... :)

unit MemoryGuard;

interface

type
{ IGuardObject }
IGuardObject = interface(IUnknown)
function Obj : Pointer;
end;

function Guard(aInstance : TObject) : IGuardObject;

implementation

type
{ TGuardObject }
TGuardObject = class(TInterfacedObject, IGuardObject)
private
fInstance : TObject;
public
function Obj : Pointer;
constructor Create(aInstance : TObject);
destructor Destroy; override;
end;

{ TGuardObject }

// _____________________________________________________________________________
constructor TGuardObject.Create(aInstance : TObject);
begin
fInstance := aInstance;
end;

// _____________________________________________________________________________
destructor TGuardObject.Destroy;
begin
fInstance.Free;
inherited;
end;

// _____________________________________________________________________________
function TGuardObject.Obj : Pointer;
begin
result := fInstance;
end;

// _____________________________________________________________________________
function Guard(aInstance : TObject) : IGuardObject;
begin
result := TGuardObject.Create(aInstance);
end;
end.

============================================================================

// ReportMemoryLeaksOnShutdown := true; => in project source

// _____________________________________________________________________________
procedure TForm24.FormCreate(Sender : TObject);
begin
// create a TStringlist with 'Guard'
list := Guard(TStringlist.Create).obj;
fill1; // fill list

// show content
ShowMessage( 'Message 1'#13#10 + list.Text );
// list.Free => no need to release the object

// exemple 2
list := Guard(TStringlist.Create).obj;
list.Add('---------------');
list.Add('memory frees itself');
list.Add('---------------');

// show content
ShowMessage( 'Message 2'#13#10 + list.Text );
// list.Free => no need to release the object
end;

// _____________________________________________________________________________
procedure TForm24.fill1;
var
i : integer;
begin
for i := 0 to 10 do
list.Add('item ' + IntToStr(i));
end;

Das könnte Ihnen auch gefallen