The liabilities of binding rvalues to ref

Jonathan M Davis jmdavisProg at gmx.com
Thu May 9 17:31:45 PDT 2013


On Friday, May 10, 2013 10:08:37 Manu wrote:
> Correct, it specifies something _entirely different_, it says "I can safely
> receive a temporary, because I promise not to escape it". This is the
> actual problem that we're trying to solve, and it addresses the problem
> head on.
> 
> As I've had to re-iterate countless times, and such is the massive fallacy
> behind all of these threads, this whole debate is NOT about
> lvalues/rvalues, and I wish people would stop using the term 'rvalue' in
> their posts, I worry that they misunderstand the problem every time it's
> said.
> 
> This code is broken:
> void f(ref int x) {}
> int x;
> f(x);
> 
> x is an lvalue.
> This is the real problem case, and addressing this will solve the rvalue
> case at the same time.
> Passing an rvalue to a function just generates an implicit temp which is
> functionally identical to the above, except the lifetime of a temp is
> usually the life of the statement rather than the outer scope.
> The problem we need to solve is that of a function being able to safely
> receive a _temporary_.

The runtime check for ref that we agreed on already solves the @safety 
problem. So, I see no point in discussing the @safety problem further unless 
there's something wrong with the runtime check solution. And yes, the @safety 
problem is not just a question of rvalues. But whether ref should accept 
rvalues is very important with regards to being able to write and understand 
correct and maintainable code.

The question of accepting rvalues that we are therefore discussing has 
_nothing_ to do with @safety. It's entirely a question of avoiding other types 
of bugs - like accepting nonsense like swap(5, 7), which in that case is 
fortunately obvious but is not obvious in the general case. IMHO, it needs to 
be clear when a function intends to take an argument by ref because it intends 
to mutate the argument and when it intends to take an argument by ref because 
it wants the efficiency boost of avoiding the copy. In the first case, it makes 
no sense to accept rvalues, and in the second case, you definitely want to 
accept rvalues. As such, having different syntax is needed (be it auto ref or 
@acceptrvalue or whatever).

I'm not entirely against adding a new attribute for that (it would have the 
added benefit of not needing a compiler optimization to guarantee that a 
templated function takes its argument by ref when passed an rvalue), but 
Walter and Andrei don't want to add new attributes if they can avoid it, so I 
don't expect them to be okay with adding a new attribute. And since auto ref 
was originally supposed to be this attribute, I'd _much_ rather have that do 
it than make the mistake of letting ref accept rvalues.

- Jonathan M Davis


More information about the Digitalmars-d mailing list