The liabilities of binding rvalues to ref

Jonathan M Davis jmdavisProg at gmx.com
Thu May 9 14:06:43 PDT 2013


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).

- Jonathan M Davis


More information about the Digitalmars-d mailing list