rvalue references

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Wed Oct 19 02:29:50 PDT 2016


On 19.10.2016 04:58, Marco Leise wrote:
> Am Tue, 18 Oct 2016 22:43:01 +0200
> schrieb Timon Gehr <timon.gehr at gmx.ch>:
>
>> It wouldn't even be the same thing if it was allowed. D const is not C++
>> const. Enforcing transitive read-only on rvalue references does not make
>> that much sense.
>
> For me using const ref vs. const is typically entirely a
> matter of avoiding a costly copy. The function body shouldn't
> care whether the data came from an rvalue or lvalue. It is
> exemplified in the following lines where doSomething takes a
> const ref and worldTransform returns by value:
>
>   const worldTransform = someObj.worldTransform();
>   otherObj.doSomething(arg1, arg2, worldTransform);
>
> I'd prefer to write:
>
>   otherObj.doSomething(arg1, arg2, someObj.worldTransform());
>
> as the temporaries add significant noise in some functions and
> make the equivalent C++ code look cleaner.
>
> It may be noteworthy that the lack of rvalue references only
> really got annoying for me with matrix calculations, because
> there are so many medium sized temporaries. Some of them come
> directly from binary operators. Functions often need to
> perform a set of computations that bare a lot of similarity,
> where visual cues help the understanding. In a reduced form:
>
>   calculate(  matrix);  // works
>   calculate(2*matrix);  // doesn't work, requires temporary
>   calculate(3*matrix);  //              "
>
> Introducing temporaries makes the similarity of the
> calculation less evident. Making calculate take auto-ref would
> result in duplicate code and thrash the instruction cache
> (especially with 2 or 3 arguments). Dropping "ref" results in
> unnecessary matrix copies at this and other call sites.
>

Yes, the lack of rvalue references can be annoying but 'const' should be 
orthogonal to any implemented solution.

There should be a way to pass rvalues by reference that are not 
prevented from being mutated, and it should be the same way as for const 
references. (For example, one possible approach is to just allow rvalues 
to bind to all 'ref' parameters (as is done for the implicit 'this' 
reference), alternatively there could be some additional "allow rvalues 
here" annotation that does not influence mutability.)


More information about the Digitalmars-d mailing list