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

Manu turkeyman at gmail.com
Sat Mar 24 17:45:54 UTC 2018


On 24 March 2018 at 07:56, kinke via Digitalmars-d
<digitalmars-d at puremagic.com> 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.
>
>> 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.

I touched on this.
It sounds reasonable at first glance. But the reasoning goes:
1. for safety reasons, we won't allow implicit stack temporaries to
pass to functions that may escape them.
2. support passing temporaries only to 'scope ref'
3. realise that the implicit temp created by an rvalue is identical to
the manually authored temp (or any other stack locals in the caller),
you find that the only reasonable option to satisfy the alleged safety
concern, is that all stack variables may never be passed to any
function that's not 'scope ref'.

Ie, you can't do this for safety reasons, because the exact same
reasoning would exclude all stack variables ever from being passed the
same way. The proposition is self-defeating.
I was attracted to this idea for a short while, until I realised it
was ridiculous. ;)


>> 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.

It's also not great for libraries. auto ref functions are template
functions... what if I want to export that function? I can't.
There are practical API and ABI reasons that you don't want every
function to be a template function.
Library authors carefully control which functions are 'real' functions
and which are templates, for a wide variety of reasons. Binary libs
are a thing. DLL's are a thing.


More information about the Digitalmars-d mailing list