[fpc-devel] Operator overloading question: Impossible to overload assignment for equal types. Why?
Bart
bartjunk64 at gmail.com
Wed Apr 24 11:59:26 CEST 2024
Hi,
Overloading the := (assignment) operator for equal types is forbidden.
Out of curiosity I would like to know why that is?
When you have e.g. a record definition containing a dynamic array, not
being able to overload the assignment operator is just a PITA.
OK, once you know why the assignment operator in such a case does not
do what you intuitively thought it would do, you just work around
this.
Just a simple example:
type
TArr = array of integer;
TRec = record
A: TArr;
end;
procedure DoItConst(const R: TRec);
var
temp: TRec;
begin
temp := R;
temp.A[0] := 111;
end;
var
R1, R2: TRec;
begin
R1.A := [1,2,3];
R2 := R1;
R2.A[0] := 666;
DoItConst(R2);
end.
After all this:
R1:
Length(R.A) = 3
R.A[0] = 111
R.A[1] = 2
R.A[2] = 666
R2:
Length(R.A) = 3
R.A[0] = 111
R.A[1] = 2
R.A[2] = 666
Yes: programmer error (PEBKAC).
(I once spent several hours to find out why my configuration got
changed after passing a property around to a procedure similar to
DoItConst ...)
So you write something like:
function AssignRec(Src: TRec): TRec;
begin
Result.A := Copy(Src.A);
end;
And then call that in every place where you intuitively would have
used the assignment operator, and avoid code like in DoIt().
In such instances it would really be helpfull if you could just
overload the assignment operator like:
operator := (Src: TRec): TRec;
begin
Result := AssignRec(Src);
end;
--
Bart
More information about the fpc-devel
mailing list