On 02.02.2023 12:19, Marco van de Voort via fpc-devel wrote:
On 2-2-2023 12:00, Ondrej Pokorny via fpc-devel wrote:
The only disadvantage is that you get a FreeAndNil copy for every type you pass into the parameter (?)
Are they actually made global ? Will two freeandnil<integers> in different units use the same?

But that is just curiousity, IMHO this remedy is worse than problem. Obviously even.

In case FreeAndNil is inlined, there is no problem, is there?

generic procedure FreeAndNil<T: TObject>(var Obj: T); inline;
var
  Temp: TObject;
begin
  Temp := Obj;
  Obj := nil;
  Temp.Free;
end;

I checked now and on i386-win32 the generic FreeAndNil is actually inlined:

program test;

{$mode objfpc}{$h+}
{$modeswitch ImplicitFunctionSpecialization}

generic procedure FreeAndNil<T: TObject>(var Obj: T);
var
  Temp: TObject;
begin
  Temp := Obj;
  Obj := nil;
  Temp.Free;
end;

type
  TSomeObject = class(TObject);
  TSomeObject2 = class(TObject);

var
  X: TSomeObject;
  X2: TSomeObject2;
const
  IsNil: array[Boolean] of string = ('nil', 'assigned');
begin
  X := TSomeObject.Create;
  X2 := TSomeObject2.Create;
  FreeAndNil(X);
  FreeAndNil(X2);
  Writeln('X  ', IsNil[Assigned(X)]);
  Writeln('X2 ', IsNil[Assigned(X2)]);

  ReadLn;
end.

So everything good!

Ondrej

_______________________________________________
fpc-devel maillist  -  fpc-devel@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel

Reply via email to