smart pointers
editSmart pointers are reference counted classes or records that encapsulate another class and add automatic management, also known as ARC: 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.
A smart pointer based on advanced records
editIt 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
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
smList:TSmartPointer<TStringlist>;
List:TStringlist;
begin
{ Use the list }
smList.Invoke.Add('some text');
{ It is also possible to assign to an
uninitialized stringlist variable }
list := smList.Invoke;
writeln(List.Text);
readln;
{ no leaks }
end.
It is enough to specialize the record to a class type, 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.
A smart pointer based on a COM interface
editAnother 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 smartcom;
{$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;
var
smList1,smList2:ISmartPointer<TStringlist>;
List:TStringlist;
begin
{ Create a normal stringlist }
List := TStringlist.Create;
{ Add Smart pointer management }
smList1 := TSmartPointer<TStringlist>.Create(List);
{ Add text to the list}
List.Add('Some text');
{ Add text to the list using the smart pointer}
smList1.Invoke.Add('Some more text');
{ Show the content }
writeln(List.Text);
{ Create a smart pointer TStringlist directly }
smList2 := TSmartPointer<TStringlist>.Create;
{ Add the content from the other list }
smList2.Invoke.Add(list.text);
{ Show the content }
writeln(smList2.invoke.Text);
{ No leaks }
end.
Observe that you can use list and smList1 interchangeably for the duration of the program.
You have seen that up until now we explicitly have to the invoke function or property to access the underlying class. Can't we get rid of that? Well, yes, but that needs FPC version 3.3.1 or higher:
A smart pointer that uses a function reference
editSee also: Feature announcement: Function References and Anonymous Functions
In version 3.3.1 function references are introduced. As the name says it is a reference to a function.
Internally function references are implemented as a COM interface with just one method:invoke. See why we used invoke throughout?
Note that for once this internal implementation is NOT implementation detail. You can count on it to always be implemented in this way.
You will see that, compared to the previous COM based approach, we need to change very little. In effect, if these were units, just the interface section needs modification.
What we get back is a much more elegant smart pointer where we can drop the invoke completely:
program smartfuncref;
{$mode delphi}{$modeswitch functionreferences}
uses
classes;
type
ISmartPointer<T> = reference to function:T;
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;
var
smList1,smList2:ISmartPointer<TStringlist>;
List:TStringlist;
begin
{ Create a normal stringlist }
List := TStringlist.Create;
{ Add Smart pointer management }
smList1 := TSmartPointer<TStringlist>.Create(List);
{ Add text to the list}
List.Add('Some text');
{ Add text to the list using the smart pointer}
smList1.Add('Some more text');
{ Show the content }
writeln(List.Text);
{ Create a smart pointer TStringlist directly }
smList2 := TSmartPointer<TStringlist>.Create;
{ Add the content from the other list }
smList2.Add(list.text);
{ Show the content }
writeln(smList2.Text);
{ No leaks }
end.
For all intend and purpose, this is practically the same code, same example as the previous COM based smart pointer type but when we use the reference based version we can drop the explicit use of invoke. This is now implicit and completely transparent. It is like a default property in its behavior.
Conclusion
editThree smart pointer solutions to use ARC style memory management.
All three work well. There are more solutions but these three form a solid basis.
Are smart pointers for you? Well, that is for you to decide. Basically not all scenario's warrant them, but carefully chosen it can be a welcome addition to your toolbox.
To keep the examples simple, we used very little overhead to protect the internal instance.
You may want to add checks if the internal instances are assigned or nil. This may be important if you accidentally call free on the class instance that is managed by the smart pointer.