[fpc-devel] Question on constref

Ondrej Pokorny lazarus at kluug.net
Thu Feb 2 12:53:57 CET 2023


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



More information about the fpc-devel mailing list