1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| unit SmartPointerClass;
interface
uses Generics.Defaults;
type TSmartPointer<T: class, constructor> = record strict private FValue: T; FFreeTheValue: IInterface; function GetValue: T; private type TFreeTheValue = class (TInterfacedObject) private fObjectToFree: TObject; public constructor Create(anObjectToFree: TObject); destructor Destroy; override; end; public constructor Create(AValue: T); overload; procedure Create; overload; class operator Implicit(AValue: T): TSmartPointer<T>; class operator Implicit(smart: TSmartPointer <T>): T; property Value: T read GetValue; end;
implementation
constructor TSmartPointer<T>.Create(AValue: T); begin FValue := AValue; FFreeTheValue := TFreeTheValue.Create(FValue); end;
procedure TSmartPointer<T>.Create; begin TSmartPointer<T>.Create (T.Create); end;
function TSmartPointer<T>.GetValue: T; begin if not Assigned(FFreeTheValue) then self := TSmartPointer<T>.Create (T.Create); Result := FValue; end;
class operator TSmartPointer<T>.Implicit(smart: TSmartPointer<T>): T; begin Result := Smart.Value; end;
class operator TSmartPointer<T>.Implicit(AValue: T): TSmartPointer<T>; begin Result := TSmartPointer<T>.Create(AValue); end;
constructor TSmartPointer<T>.TFreeTheValue.Create(anObjectToFree: TObject); begin fObjectToFree := anObjectToFree; end;
destructor TSmartPointer<T>.TFreeTheValue.Destroy; begin fObjectToFree.Free; inherited; end;
end.
|