[fpc-devel] class operator overloads

Ryan Joseph ryan at thealchemistguild.com
Wed Apr 17 02:43:00 CEST 2019

> On Apr 16, 2019, at 6:10 PM, Sven Barth via fpc-devel <fpc-devel at lists.freepascal.org> wrote:
> Mutating is also not the solution. Consider this:
> === code begin ===
> operator + (aLeft, aRight: TSomeClass): TSomeClass;
> begin
>   aLeft.DoSomething(aRight);
>   Result := aLeft;
> end;
> var
>   a, b, c: TSomeClass;
> begin
>   a := TSomeClass.Create;
>   b := TSomeClass.Create;
>   c := a + b;
>   a.Free;
>   b.Free;
>   c.Free; (* boom! *)
> end.
> === code end ===
> A user does not necessarily know what an operator overload does.
> For records and TP style objects this is not a problem, because they are copied, but for classes only their pointer is copied (and this either leads to the above problem or memory leaks if temps are involved).
> Regards,
> Sven

I see why that could be a problem but aren’t users reasonable for not doing dangerous things in a language like Pascal with low-level memory access? They can already do this anyways via operator functions so it’s already too late. :) If you want a language that prioritizes safety then Pascal is already a bad choice so I think most people know how to be safe.

What this means is that’s it harder for more advanced programmers to do things like add + and := operator to collection classes like arrays and that’s pretty unfortunate. At this point it’s already been smuggled in via operator functions so I think the team should reconsider allowing them for classes.

	Ryan Joseph

More information about the fpc-devel mailing list