To fully support what you need, the language must support 2 things:
- Garbage collector. This is the only thing that gives you the freedom to USE something without worrying about releasing it. I would welcome changes in Delphi that even gave us partial support for this.
- Ability to define local initialized variables. Again, I would love to see something like that.
Meanwhile, closest you can use interfaces instead of garbage collection (since interfaces are counted by reference, as soon as they go out of scope they will be released). Regarding initialized local variables, you can use a trick similar to what I describe here: Declaring block level variables for branches in delphi
And for fun, here's a console application that demonstrates the use of "fake" local variables and interfaces to get temporary lists that are easy to initialize, will be automatically released:
program Project1; {$APPTYPE CONSOLE} uses SysUtils, Generics.Collections; type ITemporaryLocalVar<T:constructor> = interface function GetL:T; property L:T read GetL; end; TTemporaryLocalVar<T:constructor> = class(TInterfacedObject, ITemporaryLocalVar<T>) public FL: T; constructor Create; destructor Destroy;override; function GetL:T; end; TTempUse = class public class function L<T:constructor>: ITemporaryLocalVar<T>; end; { TTemporaryLocalVar<T> } constructor TTemporaryLocalVar<T>.Create; begin FL := T.Create; end; destructor TTemporaryLocalVar<T>.Destroy; begin TObject(FL).Free; inherited; end; function TTemporaryLocalVar<T>.GetL: T; begin Result := FL; end; { TTempUse } class function TTempUse.L<T>: ITemporaryLocalVar<T>; begin Result := TTemporaryLocalVar<T>.Create; end; var i:Integer; begin try with TTempUse.L<TList<Integer>> do begin L.Add(1); L.Add(2); L.Add(3); for i in L do WriteLn(i); end; ReadLn; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
Cosmin prund
source share