The liabilities of binding rvalues to ref

Steven Schveighoffer schveiguy at yahoo.com
Thu May 9 14:23:03 PDT 2013


On Thu, 09 May 2013 17:06:43 -0400, Jonathan M Davis <jmdavisProg at gmx.com>  
wrote:

> On Thursday, May 09, 2013 16:59:13 Steven Schveighoffer wrote:
>> Why is it so bad that that is legal? Really hard to stop people from
>> writing incorrect code. In your case, it actually LOOKS wrong, so that's
>> not really a case we should be concerned about.
>
> The problem is that while it's obvious in the swap case, it's not always
> obvious. And when you look at a function signature and see that it  
> accepts its
> argument by ref (and therefore doesn't accept rvalues), you can  
> reasonably
> assume that it's intended to alter its argument, whereas if it takes by  
> auto
> ref (which then would accept rvalues), you know that the intention is  
> for the
> function to accept arguments by ref for efficiency and not for mutation.  
> You do
> need const to fully guarantee that, but it still gives a definite  
> indicator of
> intent even without that (and const is too restrictive for some cases to
> require it). And if ref accepted rvalues, you'd end up with functions  
> using
> ref as a matter of course for the efficiency gain (as occurs in C++ with  
> const&)
> and wouldn't have a clue which ones were intended to mutate their  
> arguments
> and which were just doing it for efficiency (since unlike C++, const  
> wouldn't be
> required and might even be avoided given how restrictive it is in D).

I understand the point, but it's not as bad as you think.  Usually you can  
discern from the function name what its going to do (e.g. the 'fix'  
function from the example).  Having a storage class that accepts by ref  
and then *might* change them is really kind of useless.  If auto ref is  
used, there should be no promises for that storage class.

In any case, I'm fine with auto ref if that is the solution.  I just  
wonder if it's worth the trouble.  I suppose we will know the answer only  
after having it implemented for a while.

-Steve


More information about the Digitalmars-d mailing list