Delphi - Generics Free

Having the following class of generics

 TTuple<T1, T2> = class
  protected
    fItem1: T1;
    fItem2: T2;
  public
    constructor Create; overload;
    constructor Create(Item1: T1; Item2: T2); overload;
    destructor Destroy; override;

    property Item1: T1 read fItem1 write fItem1;
    property Item2: T2 read fItem2 write fItem2;
  end;

constructor TTuple<T1, T2>.Create;
begin
  inherited;
end;

constructor TTuple<T1, T2>.Create(Item1: T1; Item2: T2);
begin
  fItem1 := Item1;
  fItem2 := Item2;
end;

destructor TTuple<T1, T2>.Destroy;
begin
  inherited;
end;

and is used in such a way as:

x := TTuple<TObjectList<TMyObjects>, Integer>.Create;

I need to install fitem1 manually for free. How can I free fItem1 inside the destructor?

+6
source share
1 answer

There are no restrictions on the type T1, T2 in the definition of TTuple. This is why you cannot call the destructor because it can be any type, double / integer, etc. Direct answer to your question:

  PObject(@fItem1).DisposeOf;

But it will work correctly only when T1 is a class. The correct solution is to define a TTuple with type restrictions:

TTuple<T1: class; T2> = class

Then you can free it in the usual way:

fItem1.Free

To do this in Delphi style, you can create two general classes:

TTuple<T1,T2> = class
...
end;

TObjectTuple<T1: class; T2> = class<TTuple<T1,T2>>
  ...
  property OwnsKey: boolean;
end;

destructor TObjectTuple<T1,T2>.destroy;
begin
  if OwnsKey then
    FItem1.DisposeOf;
end;

, ,

TObjectList<T: class>
+7

All Articles