下面把測試程序改一下,讓智能指針與集合結合測試:
program TestAutoPtrList;
{$APPTYPE CONSOLE}
uses
SysUtils,
Generics.Collections,
AutoPtr in 'AutoPtr.pas';
type
TTestClass = class
private
fInt: Integer;
public
constructor Create(aInt: Integer); virtual;
destructor Destroy; override;
procedure DoPrintInt;
end;
var
gList: TList<IAutoPtr<TTestClass>>;
gAp: IAutoPtr<TTestClass>;
{ TTestClass }
constructor TTestClass.Create(aInt: Integer);
begin
fInt := aInt;
Writeln('Create');
end;
destructor TTestClass.Destroy;
begin
Writeln('Destroy');
inherited;
end;
procedure TTestClass.DoPrintInt;
begin
Writeln(fInt);
end;
procedure DoTestAutoPtr;
var
ap: IAutoPtr<TTestClass>;
n: Integer;
begin
gList := TList<IAutoPtr<TTestClass>>.Create;
for n := 0 to 2 do
begin
ap := TAutoPtr<TTestClass>.New(TTestClass.Create(10));
ap.Get.DoPrintInt;
gList.Add(ap);
ap := nil;
end;
Writeln('Save an AutoPtr');
gAp := gList[1];
Writeln('gList Destroy');
gList.Free;
Writeln('Set saved AutoPtr = nil');
gAp := nil;
end;
begin
DoTestAutoPtr;
Readln;
end.
測試結果: