[fpc-devel] class operator overloads
Sven Barth
pascaldragon at googlemail.com
Wed Apr 17 00:10:53 CEST 2019
Am 16.04.2019 um 22:59 schrieb Ryan Joseph:
>
>> On Apr 16, 2019, at 4:51 PM, Sven Barth via fpc-devel <fpc-devel at lists.freepascal.org> wrote:
>>
>> It's the same problem there.
>> The thing however is that FPC's operator overloading support is quite old (compared to Delphi's) and it's possible that it is even older than the support for Delphi's class type. So the global operators simply gained support for classes by "accident" while the ones nested in records came much later by choice. Adding support for operators inside classes would be a choice as well.
> Ok now I finally understand. So why is this really a problem? It just means the operator needs to mutate the actual class instead of making a copy like for records, but those are the rules anyways. Given that I still don’t understand why "class operator” isn’t included in classes.
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
More information about the fpc-devel
mailing list