The liabilities of binding rvalues to ref

Jonathan M Davis jmdavisProg at gmx.com
Thu May 9 22:19:31 PDT 2013


On Friday, May 10, 2013 07:01:21 deadalnix wrote:
> On Friday, 10 May 2013 at 04:44:29 UTC, Jonathan M Davis wrote:
> >> 2. We could say UFCS has an implicit ref-at-callsite if
> >> needed, and will
> >> not compile for rvalues.  If you think about it, 'this' is
> >> implicitly ref,
> >> and UFCS is calling like the first argument is the 'this'
> >> reference.
> > 
> > That would make using UFCS with ranges generally illegal, as
> > most range-based
> > funtions do not have ref parameters, and you generally don't
> > want them to be
> > passed by ref.
> 
> Why ? Range behavior is undefined when passed by value.

In some cases you don't care, but ranges are almost always passed by value, 
and when you're worried about ranges being reference types, you call save, 
meaning that if you're chaining, you're even more likely to passing an rvalue. 
And even if a range is a reference type, it's frequently not an lvalue, 
because it's frequently the return value of a function, and it's frequently 
the case that such return values can't be returned by ref, so requiring ref 
for UFCS would have a tendency to kill function chaining via UFCS.

> > On the other hand, if ref at the callsite is optional, then the
> > lack of ref at
> > the call site means absolutely nothing. You're still going to
> > have to look at
> > every single function signature to determine if it takes a ref
> > argument or
> > not, meaning that the lack of ref at the call site buys you
> > nothing at best
> > and harms you at worst, because it gives you a false sense of
> > security that
> > the argument is not being passed by ref. Programmers would have
> > to be 100%
> > consistent in using ref at the callsite to avoid that, and
> > that's obviously
> > not going to happen.
> 
> It make sense when you pass by ref to modify things. In this case
> passing an rvalue don't make any sense. If you di it for
> performance, then this is yet another instance of the compiler
> rewriting things to improve performances.

The only time that it would make sense to put ref at the callsite is if you 
intend to mutate the object (and the ref at the callsite is then intended to 
signal that to the programmer as well as get the compiler to verify that it's 
being passed by ref). If plain ref were to accept rvalues, then ref at the 
callsite would be pretty much meaningless. And it would never make sense to 
use it with something like auto ref.

- Jonathan M Davis


More information about the Digitalmars-d mailing list