16842, “e-kayrakli”, “Should there be any limitations on operator arguments’ constness?”, “2020-12-09T23:04:47Z”
The code below shows that one can overload +
operator on a type in a way that it can modify its arguments.
record R { var x = 10; }
proc +(ref lhs: R, ref rhs: R) {
lhs.x += rhs.x;
return lhs;
}
var r1: R;
var r2: R;
var a = r1 + r2; // r1 is modified in this line
writeln(r1); // prints x=20
I’d argue that this should be prevented by requiring some args to operators to be const
. In that world, the above snippet would result in a compiler error on the proc +
definition, saying that the arguments to +
must be const.
Although more freedom to the implementer can be nice, I think such (ab)uses of operators can make reading the code really difficult.