Smartpointers

This is an old revision of Smartpointers, edited by Thaddy at . The current revision is 150388.

/* smart pointers */

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
  FInvoke:T;
  public 
  class operator initialize(var value: TSmartPointer<T>);
  class operator finalize(var value: TSmartPointer<T>);
  function invoke:T;
  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;
  
  function TSmartPointer<T>.Invoke:T;
  begin
    Result := FInvoke;
  end;
  
var
  List:TSmartPointer<TStringlist>;  
begin
  List.Invoke.Add('some text');
  writeln(List.Invoke.Text);
  readln;
  { no leaks }
end.