Rvalue references

Steven Schveighoffer schveiguy at yahoo.com
Wed Jan 10 01:56:02 UTC 2018


On 1/8/18 6:07 PM, Jiyan wrote:
> 
> Sry i know i asked it already in IRC:
> Are rvalue references already solved with auto ref?
> 
> https://p0nce.github.io/d-idioms/#Rvalue-references:-Understanding-auto-ref-and-then-not-using-it 
> 
> 
> Says rvalues are moved!

But an rvalue move is cheaper. You construct it right on the stack where 
it needs to be, and no actual copy is happening. Then inside the 
function, no further indirections are needed, just stack offsets.

> The other solution seems not so practical.

The other solution exploits a hole in the "rvalues cannot be references" 
mantra. Because all member functions take 'this' by reference, the 
function call can be used to blur the line between rvalues and lvalues.

It makes for some... interesting things:

struct Int
{
    int value;
    Int opBinary(string op : "+")(ref const Int other) const
    {
        return Int(other.value + value);
    }
}

auto v = Int(5);

auto v2 = s + Int(5); // error
auto v3 = Int(5) + s; // OK!

> Is any solution to them intended, or was all the talk about rvalue 
> references simply discarded?

auto ref was actually proposed as a non-template solution, but Walter 
implemented it the way it is now. The original proposal would have meant 
that rvalue references like C++ were possible (without conflating it 
with const).

But current auto ref is what we have, so I would recommend using it.

-Steve


More information about the Digitalmars-d-learn mailing list