rvalue references

Jonathan M Davis jmdavisProg at gmx.com
Fri Apr 26 19:26:12 PDT 2013


On Saturday, April 27, 2013 10:21:32 Manu wrote:
> > > Why bother with 'auto'? Why not just make this default behaviour?
> > 
> > For the same reason that T& doesn't take rvalues in C++ while const T&
> > does.
> > There's a big difference between wanting an argument to be passed as
> > efficiently
> > as possible and specifically wanting to alter the argument being passed
> > in.
> > Plain ref is for cases where you explicitly want to mutate the argument.
> > You're just asking for bugs if you allow ref to accept rvalues. We've had
> > problems like this before when some literals were treated as lvalues. The
> > behavior of a function which takes its argument by ref and the behavior of
> > one
> > which takes its argument by auto ref are fundamentally different.
> 
> So you're saying it should be const ref instead of auto ref...
> I agree.

Not at all. const is so much more restrictive in D that it really doesn't make 
sense to have const be required in order to be able to pass an argument to a 
function efficiently without caring whether it's an rvalue or an lvalue. auto 
ref permits const but doesn't require it - which is what we need - whereas 
const ref is always const.

I'm arguing that we need an attribute which differs from naked ref which 
indicates that the function doesn't care whether it's given an lvalue or an 
rvalue - it just wants it to be passed as efficiently as possible. auto ref is 
supposed to serve this purpose. Naked ref on the other hand is specifically for 
when the function needs to alter the argument and not a copy of the argument. 
const ref is ultimately kind of useless IMHO.

The only real hangup with that at this point is that templated functions 
should be able to use the auto ref solution that non-templated functions 
should use (invisibly creating a variable when an rvalue is passed so that an 
lvalue can be passed), but we also need the current auto ref functionality 
that we have for templated functions. So, either we need a new attribute, or 
we need to do what Timon suggested and make the compiler smart enough to figure 
out when it can get away with using the non-templated auto ref solution with a 
templated function without changing the function's semantics.

- Jonathan M Davis


More information about the Digitalmars-d mailing list