smart pointers
Smart pointers are reference counted classes or records that encapsulate another class and adds automatic management: The contained class and the smart pointer are automatically freed when they go out of scope. There are several ways to write smart pointers, for example using advanced records or using COM style interfaces.
1. A smart pointer based on advanced records
It is very simple to create a generic smartpointer record that can encapsulate classes with parameterless constructors. The memory management, class creation and class destruction is simply done through the instance of the record You just have to declare a variable:
program smartrec;
{ A simple smart pointer based on advanced records.
Works for classes with parameterless constructors }
{$mode delphi}
uses classes;
type
TSmartPointer<T:class, constructor> = record
private
FInvoke:T;
public
class operator initialize(var value: TSmartPointer<T>);
class operator finalize(var value: TSmartPointer<T>);
property invoke:T read FInvoke;
end;
class operator TSmartPointer<T>.initialize(var value: TSmartPointer<T>);
begin
Value.FInvoke := T.Create;
end;
class operator TSmartPointer<T>.finalize(var value: TSmartPointer<T>);
begin
Value.FInvoke.Free;
end;
var
List:TSmartPointer<TStringlist>;
begin
List.Invoke.Add('some text');
writeln(List.Invoke.Text);
readln;
{ no leaks }
end.
It is enough to specialize the record to a class instance, like in this case a TStringlist. The record creates and destroys the class automatically and the class is accessible through the invoke property. Note: the reason it is named "invoke" will become clear later, it is a matter of consistency.
Observe that the stringlist needs no free call: that is done automatically when the record goes out of scope through its finalize operator.
2. A smart pointer based on a COM interface
Another approach to create smart pointers is to use a COM interface. This works out quite similar to the record based method but can have some advantages. We can use this smart pointer version in two ways: Like the record, create the instance automatically Encapsulate an existing instance and add automatic management to it
program smartcom1;
{$mode delphi}
uses
classes;
type
ISmartPointer<T> = interface
function invoke:T;
end;
TSmartPointer<T: class, constructor> = class(TInterfacedObject, ISmartPointer<T>)
private
FValue: T;
public
constructor Create; overload;
constructor Create(const AValue: T); overload;
destructor Destroy; override;
{ implement the interface }
function invoke: T;
end;
constructor TSmartPointer<T>.Create;
begin
inherited Create;
FValue := T.Create;
end;
constructor TSmartPointer<T>.Create(const AValue: T);
begin
inherited Create;
FValue := AValue;
end;
destructor TSmartPointer<T>.Destroy;
begin
FValue.Free;
inherited;
end;
function TSmartPointer<T>.Invoke:T;
begin
Result := FValue;
end;
begin
end.