rvalues -> ref (yup... again!)

Atila Neves atila.neves at gmail.com
Mon Mar 26 14:40:03 UTC 2018


On Friday, 23 March 2018 at 22:01:44 UTC, Manu wrote:
> Forked from the x^^y thread...
> <snip>

There are too many replies on this thread, addressing all the 
comments would take forever and pollute the thread itself. So 
forgive me if I say something that was covered already by someone 
else.

AFAIK being able to bind rvalues to `ref const(T)`, only makes 
sense when calling C++ functions that take `const T&` (especially 
since that is common). I have not yet heard any other use for 
them. I'd be in favour of allowing it _only_ for `extern(C++)` 
functions. Otherwise use `auto ref` or have overloads for 
pass-by-value and pass-by-ref.
I too, once a recent immigrant from the lands of C++, used to 
keep writing `ref const(T)`. I just pass by value now.

C++ T&& (forwarding reference) -> D auto ref T
C++ T&& (Rvalue reference) -> D T
C++ const T& -> D T
C++ T& -> D ref T

If replacing const T& with T chafes, I understand. I used to feel 
that way too. It's _possible_ that would incur a penalty in 
copying/moving, but IME the cost is either 0, negligible, or 
negative (!).

As mentioned above, if calling C++ code there's no choice about 
using T instead of const T&, so for pragmatic reasons that should 
be allowed. But only there, because...

> Can you please explain these 'weirdities'?
> What are said "major unintended consequences"?

Rvalue references. They exist because of being able to bind 
temporaries to const T& in C++, which means there's no way of 
knowing if your const T& was originally a temporary or not. To 
disambiguate C++11 introduced the type system horror that are 
rvalue references (which also do double-duty in enabling perfect 
forwarding!).

D doesn't have or need rvalue references _because_ of not 
allowing temporaries to bind to ref const(T). You get move 
semantics in D without the pain. That's a win in my book.

Atila



More information about the Digitalmars-d mailing list