Stronugly-typed smart pointers are now possible in Delphi, leveraging the work on generics. Here's a simple smart pointer type:
TSmartPointer <T: class> = record
Strict private
FValue: T;
FLifetime: IInterface;
Public
Constructor Create (const AValue: T); overload;
Class operator Implicit (const AValue: T): TSmartPointer <T>;
Property Value: T read FValue;
End;
Here it is in action, where TLifetimeWatcher is a little class that executes some code when it dies:
Procedure UseIt;
Var
X: TSmartPointer <TLifetimeWatcher>;
Begin
X: = TLifetimeWatcher. Create (procedure
Begin
Writeln ('I died .');
End );
End;
Here's the full project code that defines TSmartPointer <>, TLifetimeWatcher, and the above test routine:
{$ Apptype console}
Uses
SysUtils;
Type
TLifetimeWatcher = class (TInterfacedObject)
Private
FWhenDone: TProc;
Public
Constructor Create (const AWhenDone: TProc );
Destructor Destroy; override;
End;
{TLifetimeWatcher}
Constructor TLifetimeWatcher. Create (const AWhenDone: TProc );
Begin
FWhenDone: = AWhenDone;
End;
Destructor TLifetimeWatcher. Destroy;
Begin
If Assigned (FWhenDone) then
FWhenDone;
Inherited;
End;
Type
TSmartPointer <T: class> = record
Strict private
FValue: T;
FLifetime: IInterface;
Public
Constructor Create (const AValue: T); overload;
Class operator Implicit (const AValue: T): TSmartPointer <T>;
Property Value: T read FValue;
End;
{TSmartPointer <T>}
Constructor TSmartPointer <T>. Create (const AValue: T );
Begin
FValue: = AValue;
FLifetime: = TLifetimeWatcher. Create (procedure
Begin
AValue. Free;
End );
End;
Class operator TSmartPointer <T>. Implicit (const AValue: T): TSmartPointer <T>;
Begin
Result: = TSmartPointer <T>. Create (AValue );
End;
Procedure UseIt;
Var
X: TSmartPointer <TLifetimeWatcher>;
Begin
X: = TLifetimeWatcher. Create (procedure
Begin
Writeln ('I died .');
End );
End;
Begin
Try
UseIt;
Readln;
Except
On E: Exception do
Writeln (E. Classname, ':', E. Message );
End;
End.
Update:Fixed capture-was capturing a location in the structure, which of course will be freely copied etc.
Original post address: http://barrkel.blogspot.com/2008/09/smart-pointers-in-delphi.html