www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is this an rvalue reference problem?

reply Gary Willoughby <dev nomad.so> writes:
See the following code:

import std.stdio;

void foo(ref int x)
{
	writefln("%s", x);
}

void main(string[] args)
{
	int y = 0;
	foo(y++);
}

When compiled it produces this error:

test.d(11): Error: function test.foo (ref int x) is not callable 
using argument types (int)

If I remove the post-increment of the y variable if works. Is 
this an rvalue reference issue? Would you expect this to work? 
Should the error message be a little more helpful?
Dec 27 2015
next sibling parent tsbockman <thomas.bockman gmail.com> writes:
On Sunday, 27 December 2015 at 16:05:39 UTC, Gary Willoughby 
wrote:
 If I remove the post-increment of the y variable if works. Is 
 this an rvalue reference issue? Would you expect this to work?
This should work with *pre*-increment, but not post-increment. Post-increment works like this: int y = 0; foo(function(ref int val){ int old = val; val += 1; return old; }(y)); `old` is just a local temporary, so it is not safe to return it by reference. Thus, it becomes an rvalue.
Dec 27 2015
prev sibling parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Sunday, 27 December 2015 at 16:05:39 UTC, Gary Willoughby 
wrote:
 void foo(ref int x)
 	foo(y++);
 If I remove the post-increment of the y variable if works. Is 
 this an rvalue reference issue?
Yes, but more than that, what, exactly, would you expect from that? The order of operations with the postfix ++ operator and ref would probably lead to confusing results anyway, so better to disallow it and force you to be a bit more clear with the code.
 Should the error message be a little more helpful?
Yeah, probably. A ref in D is only allowed on lvalues... lvalue gets its name from being on the left side of an equal sign when assigning, as opposed to rvalues which are on the right side of the equal sign when assigning. So if y++ = 0; doesn't compile, it will complain "y++ is not an lvalue" because it can't work on the left side of that assignment. ref in D is a proxy for assignment which is why it has this requirement.
Dec 27 2015
parent Gary Willoughby <dev nomad.so> writes:
On Sunday, 27 December 2015 at 18:54:25 UTC, Adam D. Ruppe wrote:
 On Sunday, 27 December 2015 at 16:05:39 UTC, Gary Willoughby 
 wrote:
 [...]
Yes, but more than that, what, exactly, would you expect from that? The order of operations with the postfix ++ operator and ref would probably lead to confusing results anyway, so better to disallow it and force you to be a bit more clear with the code. [...]
Thanks guys, I thought as much.
Dec 27 2015