On 14.05.21 12:00, PinDPlugga wrote:
Hi thank you both for your answers. I had understood from an earlier
chapter how this could introduce a bug, but I was confused because the
warning suggests attaching ```return``` to the parameter, which is empty
in the declaration.
`this` is considered a hidden parameter. Every non-static method has it.
So my next question would be how come ref based operator overloads are
not labelled as return and do not show this warning?
``` D
struct Fraction {
auto n = 0L;
auto d = 1L;
ref Fraction opUnary(string op)()
if (op == "++") {
n += d;
return this;
}
}
ref Fraction foo() {
auto f = Fraction(1, 3);
// Same bug as with reduce
return ++f;
}
```
Note that opUnary is not an ordinary method. It's a template. That means
attributes are inferred [1], including the `return` attribute. I.e., the
compiler adds `return` to the signature for you, just like Steven
suggested you do manually.
Try omitting the return type of `reduce` in your original code:
ref reduce() { ... }
That also enables attribute inference, and your code will compile.
[1] https://dlang.org/spec/function.html#function-attribute-inference