[fpc-devel] Question on constref
    Ondrej Pokorny 
    lazarus at kluug.net
       
    Thu Feb  2 12:00:31 CET 2023
    
    
  
On 02.02.2023 11:00, Michael Van Canneyt via fpc-devel wrote:
> In userspace, the best seems
>
> Function FreeAndNil<T :TObject>(Obj : T) : T;
>
> begin
>   Obj.Free;
>   Result:=Nil;
> end;
>
> With automatic type inference for generics, this allows you to do
>
> A:=FreeAndNil(A);
Michael, bringing your idea to the next step, FPC can do it !!!
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);
var
   X: TSomeObject;
begin
   X := TSomeObject.Create;
   FreeAndNil(X);
   if Assigned(X) then
     Writeln('assigned')
   else
     Writeln('nil');
   ReadLn;
end.
-----
Delphi cannot do it. FPC rocks!
The only disadvantage is that you get a FreeAndNil copy for every type 
you pass into the parameter (?)
Do we want to change it in SysUtils? :)
Ondrej
    
    
More information about the fpc-devel
mailing list