meaning of "auto ref const"?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Dec 20 11:24:32 PST 2016
As a general rule, 'auto ref' should probably be const. If the purpose
of 'ref' is so that the argument would be mutated, then allowing a copy
of an rvalue to this function could very well be a bug:
struct S {
int i;
}
void foo()(auto ref S s) {
s.i = 42; // <-- Cannot be observed if the arg is rvalue
}
void main() {
foo(S(1));
}
To contradict myself (and I hate when I do that! :p), the function may
be using the rvalue in a non-const context, which would make the
mutation observable:
struct S {
int i;
void sayIt() {
import std.stdio;
writeln(i);
}
}
void foo()(auto ref S s) {
s.i = 42;
s.sayIt(); // <-- Here
}
// ...
Another one through the return value (but this time it's a copy anyway,
perhaps defeating the 'ref' purpose):
// ...
S foo()(auto ref S s) {
s.i = 42;
return s;
}
void main() {
foo(S(1)).sayIt(); // <-- Here
}
Ali
More information about the Digitalmars-d-learn
mailing list