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

Timon Gehr timon.gehr at gmx.ch
Sat Mar 24 15:36:14 UTC 2018


On 24.03.2018 15:56, kinke wrote:
> On Saturday, 24 March 2018 at 13:49:13 UTC, Timon Gehr wrote:
>> What I'm saying is that I don't really buy Jonathan's argument. 
>> Basically, you should just pass the correct arguments to functions, as 
>> you always need to do. If you cannot use the result of some mutation 
>> that you need to use, you will probably notice.
> 
> I agree, but restricting it to const ref would be enough for almost all 
> of my use cases. The MS C++ compiler just emits a warning when binding 
> an rvalue to a mutable ref ('nonstandard extension used'), I'd find that 
> absolutely viable for D too.
> ...

A warning is not viable. (There's no good way to fix it.)

>> There are only three sensible ways to fix the problem:
>>
>> 1. Just allow rvalue arguments to bind to ref parameters. (My 
>> preferred solution, though it will make the overloading rules slightly 
>> more complicated.)
> 
> I always thought the main concern was potential escaping refs to the 
> rvalue, which would be solvable by allowing rvalues to be bound to 
> `scope ref` params only. That'd be my preferred choice as well.
> ...

There is no difference between escaping refs to an rvalue and escaping 
refs to a short-lived lvalue, as the callee has no idea where the 
address is coming from anyway. According to Walter, ref parameters are 
not supposed to be escaped, and @safe will enforce it.

Also, AFAIU, "scope" in "scope ref T" already applies to "T", not "ref".

>> 2. Add some _new_ annotation for ref parameters that signifies that 
>> you want the same treatment for them that the implicit 'this' 
>> reference gets. (A close second.)
> 
> *Shudder*.
> ...

Well, it beats "const".

>> 3. Continue to require code bloat (auto ref) or manual boilerplate 
>> (overloads). (I'm not very fond of this option, but it does not 
>> require a language change.)
> 
> While `auto ref` seems to have worked out surprisingly well for code 
> written in D, it doesn't solve the problem when interfacing with (many) 
> external C++ functions taking structs (represented in D by structs as 
> well) by (mostly const) ref. You're forced to declare lvalues for all of 
> these args, uglifying the code substantially.

You can add additional overloads on the D side. (This can even be 
automated using a string mixin.)


More information about the Digitalmars-d mailing list