[fpc-devel]Nested function as argument for TList.Sort

Michael Van Canneyt michael.vancanneyt at wisa.be
Thu Nov 27 09:42:08 CET 2003


On Thu, 27 Nov 2003, Marc Weustink wrote:

> At 08:54 27-11-2003, Florian Klaempfl wrote:
> >Pedro Lopez-Cabanillas wrote:
> >
> >>Hi,
> >>The attached program compiles and works fine under Kylix 3, and also
> >>compiles under fpc 1.9, but bombs with this message:
> >>An unhandled exception occurred at 0x0807F0B5 :
> >>EAccessViolation : Access violation
> >>   0x0807F0B5
> >>It happens on TObjectList.Sort when the argument is a local nested
> >>function. It works well when the argument is a global function.
> >>Regards,
> >>Pedro
> >>
> >>------------------------------------------------------------------------
> >>program test6;
> >>{$IFDEF FPC}
> >>   {$MODE DELPHI}
> >>{$ENDIF}
> >>uses
> >>   Contnrs;
> >>type
> >>   TestClass = class
> >>   private
> >>     key: Integer;
> >>   public
> >>     constructor Create(keyValue: Integer);
> >>     function getKey: Integer;
> >>   end;
> >>   constructor TestClass.Create(keyValue: Integer);
> >>   begin
> >>     key := keyValue;
> >>   end;
> >>   function TestClass.getKey: Integer;
> >>   begin
> >>     Result := key;
> >>   end;
> >>var
> >>   list: TObjectList;
> >>   procedure Populate;
> >>   begin
> >>     list := TObjectList.Create;
> >>     list.add(TestClass.Create(10));
> >>     list.add(TestClass.Create(5));
> >>     list.add(TestClass.Create(25));
> >>     list.add(TestClass.Create(15));
> >>   end;
> >>   procedure SortAndPrint;
> >>     function TestCompare(ptr1, ptr2: pointer): Integer;
> >>     var
> >>       int1, int2: Integer;
> >>     begin
> >>       int1 := TestClass(ptr1).getKey;
> >>       int2 := TestClass(ptr2).getKey;
> >>       if int1 = int2
> >>       then Result := 0
> >>       else if int1 < int2
> >>            then Result := -1
> >>            else Result := 1;
> >>     end;
> >>   var
> >>     i: Integer;
> >>   begin
> >>     list.Sort(@TestCompare);
> >>     for i := 0 to list.Count-1 do
> >>     begin
> >>       WriteLn('Item ', i, ', key = ', TestClass(list.Items[i]).getKey);
> >>     end;
> >>   end;
> >>begin
> >>   Populate;
> >>   SortAndPrint;
> >>end.
> >
> >This is bad coding imho and works in Delphi only "by accident" because
> >Delphi uses register calling conventions. Or are I'am wrong and sort
> >expects a local procedure?
>
> AFAIK it is illegal in D5 to use a local procedure for TList.Sort. Don't
> know if it is still the case in later versions (I haven't tried it and
> don't expect it)  In D1 (or earlier ?) it was legal to do this

It is illegal.

Michael.




More information about the fpc-devel mailing list