Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pmcgee69/b1aad47c3a3daa7eea348ee77da2e70e to your computer and use it in GitHub Desktop.
Save pmcgee69/b1aad47c3a3daa7eea348ee77da2e70e to your computer and use it in GitHub Desktop.
A Delphi Console Application to illustrate Automatic Reference Counting (Simplified)
program AutoFreeTest;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
System.Classes;
type
IAutoFree = interface
['{5B50A2CD-68B7-4018-A59A-504F64457645}']
function GetObj: TObject;
procedure SetObj(Value: TObject);
property Obj: TObject read GetObj write SetObj;
end;
type
TAutoFree = class(TInterfacedObject, IAutoFree)
strict private
FObj: TObject;
FMsg: string;
strict private
function GetObj: TObject;
procedure SetObj(Value: TObject);
public
constructor Create(RefObj: TObject; const pMsg: string);
destructor Destroy; override;
end;
function AutoFree(RefObj: TObject; const pMsg: string): IAutoFree;
begin
Writeln('Inside AutoFree - ' + pMsg);
Result := TAutoFree.Create(RefObj, pMsg);
end;
procedure InsertLinesStringList(pList: TStringList; AListID: String);
begin
pList.Add(AListID + ' line1');
pList.Add(AListID + ' line2');
pList.Add(AListID + ' line3');
end;
procedure PrintStringList(pList: TStringList);
var
Item: string;
begin
for Item in pList do
Writeln(Item);
end;
{ TAutoFree }
constructor TAutoFree.Create(RefObj: TObject; const pMsg: string);
begin
Writeln('Inside TAutoFree.Create - ' + pMsg);
inherited Create;
FMsg := pMsg;
FObj := RefObj;
end;
destructor TAutoFree.Destroy;
begin
Writeln('Inside TAutoFree.Destroy - ' + FMsg);
FreeAndNil(FObj);
inherited;
end;
function TAutoFree.GetObj: TObject;
begin
Result := FObj;
end;
procedure TAutoFree.SetObj(Value: TObject);
begin
FObj := Value;
end;
procedure Teste;
var
List1: TStringList;
List2: TStringList;
temp1: IAutoFree;
temp2: IAutoFree;
begin
try
Writeln('Create List1');
List1 := TStringList.Create;
temp1 := AutoFree(List1, 'OK 1');
InsertLinesStringList(List1, 'List1');
PrintStringList(List1);
Writeln('After Create List1');
Writeln('Create List2');
List2 := TStringList.Create;
temp2 := AutoFree(List2, 'OK 2');
InsertLinesStringList(List2, 'List2');
PrintStringList(List2);
Writeln('After Create List2');
if not Assigned(List1) then
Writeln('List1 is not assigned');
if not Assigned(List2) then
Writeln('List2 is not assigned');
if not Assigned(temp1) then
Writeln('temp1 is not assigned');
if not Assigned(temp2) then
Writeln('temp2 is not assigned');
PrintStringList(List1);
PrintStringList(List2);
Writeln('End');
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end;
begin
ReportMemoryLeaksOnShutdown := True;
try
Teste;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment