Issue 1974 - What's your opinion?
ShadoLight
ettienne.gilbert at gmail.com
Thu Oct 24 11:50:32 UTC 2019
On Thursday, 24 October 2019 at 08:02:28 UTC, RazvanN wrote:
> Hello everyone,
>
> I am currently trying to solve old issues but some of them I'm
> not entirely sure how to handle. One of them is 1974 [1].
> Here's the thing:
>
> struct Foo { int y; void opAddAssign(int z) { y += z; } }
> struct Bar { Foo fou; Foo test() { return fou; } }
> void main() {
> Bar x;
> x.fou.y = 0;
> x.test() += 1337;
> writefln(x.fou.y);
> }
>
> The problem is that x.test() += 1337; calls opAddAssign on a
> temporary and the person that filed the bug report claimed that
> this should be an error since the call is useless (in this
> case).
>
> I have responded to the issue with the following:
>
> "This is a bit problematic because there are 2 points of view
> on this:
>
> 1. From a high-level point of view, the bug report is valid,
> you are trying to assign to an rvalue (x.test() = x.test() +
> 1337) which should an error.
>
> 2. From a lowering point of view you are basically calling the
> member function of a temporary object
> (x.test.opAddAssign(1337)), which by the current rules is valid
> behavior.
>
> I guess that what could be implemented is something along the
> lines of: if the opAssign/op*Assign function is pure, then you
> can error/warn because the call has no effect, otherwise it is
> possible that the assign function has side effects so calling
> it is correct."
>
> What are your thoughts on this? Should be close the issue as an
> invalid one?
>
> Cheers,
> RazvanN
>
> [1] https://issues.dlang.org/show_bug.cgi?id=1974
Since it is in fact assigning to a rvalue, I would argue the
current behaviour is in fact correct - the same way as calling a
pure function without taking its return value...
int zoo(int x) pure { //pure, so guaranteed no side-effects
return x + 3;
}
...
zoo(6);
... is also 'useless', yet, completely legal code
To make it work, you can simply do...
ref Foo test()
{
return fou;
}
...which turns it into an lvalue - to which you can assign.
This is completely in line with how rvalues and lvalues behave,
so I would vote for closing as invalid issue.
More information about the Digitalmars-d
mailing list