20472, "benharsh", "Should compiler-generated assignment use field accessors?", "2022-08-18T20:23:39Z"
opened 08:23PM - 18 Aug 22 UTC
Consider the following program:
```chpl
record R {
var x : int;
pr… oc x ref {
writeln("R.x accessor");
return x;
}
}
proc main() {
var a = new R(5);
var b = new R(10);
writeln("-----");
a = b;
writeln("-----");
writeln(a);
writeln(b);
}
```
This program currently prints:
```
-----
-----
(x = 10)
(x = 10)
```
Should a user expect their field accessor to be invoked by the compiler-generated ``=`` operator overload?
The user-defined version might look like this:
```chpl
// Can add these at the end of the previous chpl snippet
operator R.=(ref lhs : R, rhs : R) {
lhs.x = rhs.x;
}
// Must implement `init=` if `=` is also implemented
proc R.init=(other:R) {
this.x = other.x;
}
```
With these additions the program outputs:
```chpl
-----
R.x accessor
R.x accessor
-----
(x = 10)
(x = 10)
```
Is there a situation in which we wouldn't want to invoke the user-defined field accessor?
Is it concerning that the compiler is generating code that users cannot write themselves?
Consider the following program:
record R {
var x : int;
proc x ref {
writeln("R.x accessor");
return x;
}
}
proc main() {
var a = new R(5);
var b = new R(10);
writeln("-----");
a = b;
writeln("-----");
writeln(a);
writeln(b);
}
This program currently prints: