Hier mal meine schnell zusammengetippte AutoPtr Klasse:
Delphi-Quellcode:
unit AutoPtr;
interface
type
IAutoPtr =
interface
function AsPointer: Pointer;
function AsObject: TObject;
end;
function CreateAutoPtr(Value: TObject): IAutoPtr;
implementation
type
TAutoPtr =
class(TInterfacedObject, IAutoPtr)
private
FValue: TObject;
public
constructor Create(AValue: TObject);
destructor Destroy;
override;
function AsPointer: Pointer;
function AsObject: TObject;
end;
function CreateAutoPtr(Value: TObject): IAutoPtr;
begin
Result := TAutoPtr.Create(Value);
end;
{ TAutoPtr }
constructor TAutoPtr.Create(AValue: TObject);
begin
inherited Create;
FValue := AValue;
end;
destructor TAutoPtr.Destroy;
begin
FValue.Free;
inherited Destroy;
end;
function TAutoPtr.AsObject: TObject;
begin
Result := FValue;
end;
function TAutoPtr.AsPointer: Pointer;
begin
Result := FValue;
end;
end.
Und hier, wie man den AutoPtr nutzt
Delphi-Quellcode:
procedure TForm1.FormCreate(Sender: TObject);
var
List, List2, List3: TList;
begin
List := CreateAutoPtr(TList.Create).AsPointer;
List2 := CreateAutoPtr(TList.Create).AsPointer;
List3 := CreateAutoPtr(TList.Create).AsPointer;
List.Add(nil);
List2.Add(nil);
List3.Add(nil);
end; // hier räumt Delphi dann automatisch auf