Why do struct literals count as lvalues?

Timon Gehr timon.gehr at gmx.ch
Fri Aug 19 05:50:14 PDT 2011


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.















More information about the Digitalmars-d mailing list