// 注意:此處如果不加as IAutoPtr<T>,程序運行時會報錯,第一次我沒有加as IAutoPtr<T>程序運行一切正常,到後面就不行了,不知道是為什麼
function TAutoPtr<T>.Release: T;
begin
Result := fObj;
fObj := nil;
end;
procedure TAutoPtr<T>.Reset(aObj: T);
begin
if aObj <> fObj then
begin
FreeAndNil(fObj);
fObj := aObj;
end;
end;
destructor TAutoPtr<T>.Destroy;
begin
if fObj <> nil then
begin
FreeAndNil(fObj);
end;
inherited;
end;
function TAutoPtr<T>.Get: T;
begin
Result := fObj;
end;
測試代碼:
program TestAutoPtr;
{$APPTYPE CONSOLE}
uses
SysUtils,
AutoPtr in 'AutoPtr.pas';
type
TTestClass = class
private
fInt: Integer;
public
constructor Create(aInt: Integer); virtual;
destructor Destroy; override;
procedure DoPrintInt;
end;
{ 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>;
begin
// 此處用Create和New都可以,因為ap對象是接口
ap := TAutoPtr<TTestClass>.Create(TTestClass.Create(10));
ap.Get.DoPrintInt; // 3*
end;
begin
DoTestAutoPtr;
Readln;
end.