Why do struct literals count as lvalues?

Timon Gehr timon.gehr at gmx.ch
Fri Aug 19 06:16:33 PDT 2011


On 08/19/2011 03:04 PM, kenji hara wrote:
> 2011/8/19 Timon Gehr<timon.gehr at gmx.ch>:
>> On 08/19/2011 02:16 PM, Steven Schveighoffer wrote:
>>>
>>> On Thu, 18 Aug 2011 18:56:01 -0400, bearophile
>>> <bearophileHUGS at lycos.com>  wrote:
>>>
>>>> Jonathan M Davis:
>>>>
>>>>> I see _zero_ reason to
>>>>> treat a newly constructed object as any different from one which is
>>>>> returned
>>>>> from a function.
>>>>
>>>> I have not followed fully this thread, so I am not sure what you are
>>>> talking about, so sorry if I am misunderstanding the whole topic.
>>>>
>>>> I assume you want to disallow code like:
>>>>
>>>> struct Vect {
>>>> float[4] data = 0.0;
>>>> // lot of operator overloading here, all arguments are by ref
>>>> }
>>>> void foo(ref Vect f) {}
>>>> void main() {
>>>> foo(Vect([1,2,3,4]));
>>>> }
>>>>
>>>> Such code is common. In foo() and in all the Vect operators ref is
>>>> required for performance. This code is quite handy. Forcing me to
>>>> define and assign a Vect to a temporary variable in main is not handy.
>>>>
>>>> Think about writing expressions that use Vects with operator
>>>> overloading, that use ref everywhere. If you can't pass and give Vects
>>>> defined inside the expressions the code becomes quite more hairy.
>>>
>>> I believe auto ref is slated to fix this problem.
>>>
>>> -Steve
>>
>> auto ref currently treats struct literals as lvalues too. (therefore, as
>> ref). And passing by value would be considerably less efficient for large
>> structs.
>>
>> As I understand it, the only issue with allowing literals and function
>> results as lvalues is that generic code cannot detect if it is working with
>> a temporary or not. I don't know if this would be useful in D though.
>>
>> each code segment of the form:
>>
>> void foo(ref S);
>> ...
>> foo(S(...));
>>
>> is equivalent to one explicitly declaring the temporary:
>>
>> {auto __temp=S(...); foo(__temp);}
>>
>> The difference is that the first is more pleasant to write. If temporaries
>> would become rvalues everyone would always have to write the second form
>> manually. So imho it is just a syntax sugar issue.
>>
>> I'd actually argue that ref-passing should work for arbitrary function
>> results too.
>
> As far as I know, Andrei's original 'auto ref' means always receive
> argument *by reference* either it is lvalue or rvalue, and it works
> with non template function.
>
> But, unfortunately, it doesn't exist in current D.
>
> Kenji Hara

Oh, interesting. So why were they implemented with different semantics 
then? Also, how would they work in a non-templated function? Would they 
just be conservatively treated as rvalues in the function body?




More information about the Digitalmars-d mailing list