On 1/30/2019 5:55 PM, Manu wrote:
lets replace 10 with a short variable named: S
"a short variable named: S" is an lvalue, so why would the rewrite be
attempted? S must be an rvalue for any rewrite to occur. We're talking
about rvalues here.
This illustrates why this should be compared with C++. Consider this C++ code:
const int& foo(const int& x) { return x; }
const int& test() {
short s;
return foo(s);
}
It compiles with clang++. The code generated for test() is:
push RBP
mov RBP,RSP
sub RSP,010h
lea RDI,-8[RBP]
movsx EAX,word ptr -2[RBP]
mov -8[RBP],EAX
call foo
add RSP,010h
pop RBP
ret
See what it is doing? It's converting s to an int, putting the int into a
temporary, then passing a reference to that temporary to foo(). So when you ask
why would a person think that this would happen with the DIP, if they know C++,
they would assume similar behavior. This is why the DIP needs to specifically
say this is not the proposed behavior. It is why a comparison to C++ behavior is
essential. It is a lot easier to understand the DIP if people can apply their
existing understanding, with a few modifications, to the D behavior. It's also
necessary to compare with C++ to see if the DIP missed something important, and
to justify any other behavioral differences.
The interesting question is, since C++ supports this behavior, what about the
truck-sized hole? The answer is in the declaration of foo(const int&). The const
is the reason. The referenced value cannot be modified. The realloc example is
blocked by the compiler.
But the DIP says const ref is not required. Therefore, copying an lvalue to a
temporary cannot be allowed, therefore implicit conversion of lvalues cannot happen.
Then we're faced with the question of if implicit conversion of lvalues is not
allowed, should implicit conversion of rvalues be allowed? I'm not so sure it
should be. For one thing, a lot of people are confused about lvalues vs rvalues,
and would find the difference in behavior puzzling. For another, it can
complicate overloading rules. I'd say allowing the conversions needs a strong
rationale.