smart pointers
Smart pointers are reference counted classes that encapsulate another class and uses automatic management: The contained class and the smart pointer are automatically freed when the 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:
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.