The liabilities of binding rvalues to ref
Steven Schveighoffer
schveiguy at yahoo.com
Thu May 9 13:59:13 PDT 2013
On Thu, 09 May 2013 16:36:27 -0400, Peter Alexander
<peter.alexander.au at gmail.com> wrote:
> On Thursday, 9 May 2013 at 18:23:12 UTC, Steven Schveighoffer wrote:
>> On Thu, 09 May 2013 13:45:16 -0400, Peter Alexander
>>> Allowing plain-old ref to bind to rvalues would be a massive mistake
>>> in my opinion. See case (2) in the original post.
>>
>> The case for it is operator overloads. Note that all operator
>> overloads are defined WITHIN types, and all operator overloads take
>> 'this' by reference. Without the hack currently in the compiler that
>> 'this' is allowed to bind by ref to rvalues, D would be near useless.
>
> C++ has this "hack" as well. Is it really a hack, or just part of the
> language design?
I should restate: The idea that restricting rvalues from binding to refs
*except* the case where it binds to 'this' is a hack. The binding to
'this' pre-dates the restriction.
>
>
>> Consider that today, this doesn't work for custom structs, unless you
>> allocate the result on the heap.
>>
>> ((a + b) + (c + d))
>
> I don't follow. You say "today", but this works for me in latest dmd. Do
> you mean hypothetically without the "hack", or am I misunderstanding?
I mean it doesn't work today if it takes the parameter by ref.
>> The original case 2 looks bad, but not very common. With by-ref
>> turning into by-value, you are in effect changing the API and
>> functionality. It would just mean that you wouldn't make that change,
>> or change the type name at the same time (so it wouldn't just compile
>> on existing code).
>
> I'm not sure about how common it is, but I really don't like the idea of
> calls like swap(1, 2) being legal. Seems like a step backward from C++.
Why is it so bad that that is legal? Really hard to stop people from
writing incorrect code. In your case, it actually LOOKS wrong, so that's
not really a case we should be concerned about. The original case 2 is
worse.
int i = 1;
swap(i, i);
That's also legal.
*(cast(int *)null) = 5;
That's also legal.
-Steve
More information about the Digitalmars-d
mailing list