auto ref is on the docket

via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 23 02:57:25 PDT 2015


On Monday, 22 June 2015 at 19:05:28 UTC, kinke wrote:
> On Monday, 22 June 2015 at 16:54:50 UTC, Marc Schütz wrote:
>> With the difference that C++ requires const-ness.
>
> Yep, so `in ref T` translating to `scope const ref T` would be 
> D's convenient and safe counterpart to C++' `const T&` 
> parameters, for their main use case: passing pure-input 
> arguments of types which are or may be costly to copy 
> (post-blit ctor, dtor, or simply big). I explicitly mention 
> 'may be' here because in templates one often doesn't know 
> (containers...).

To clarify: What I meant by my comment was that const-ness should 
not be a precondition for allowing rvalue refs. Mutable rvalue 
refs are fine.

>
> As I have already pointed out in another thread, I'd go one 
> step further and propose an extremely convenient `in T` for 
> this very common use case:
>
> * The argument is passed by value (`const T`) if the compiler 
> assumes moving/copying is more efficient than passing a 
> reference (with its indirection on the callee side) for the 
> particular target environment (hardware, ABI), e.g., for 
> plain-old-datatypes T fitting into 1-2 registers, and Object 
> references obviously.
> * Otherwise, the argument is passed by-ref (`in ref T`). As `in 
> T` doesn't mention any ref at all, it's clear that the hidden 
> reference cannot escape.

Theoretically, `immutable ref` by itself would already allow 
these semantics (without the `scope` that `in` implies). Because 
(disregarding identity/addresses) for an immutable object there 
is no observable difference between pass-by-value and 
pass-by-reference. The same is not always true for `const ref`, 
whenever aliasing is possible:

     void foo(const ref int a, ref int b) {
         int x = a;
         b++;
         assert(x == a); // can fail if both refer to the same 
variable
         // similar with global variables
     }

To guarantee this from the caller's POV, the callee must be pure 
and the parameters must be known not to alias each other.


More information about the Digitalmars-d mailing list