On 5/6/13 12:48 PM, Steven Schveighoffer wrote:
On Mon, 06 May 2013 06:43:38 -0700, Andrei Alexandrescu
<[email protected]> wrote:
I think we can technically make the overloading work while also
allowing binding rvalues to ref. But that wouldn't help any. Consider:
ref int min(ref int a, ref int b) { return b < a ? b : a; }
...
int x;
fun(min(x, 100));
Here the result of min may be bound to an lvalue or an rvalue
depending on a condition. In the latter case, combined with D's
propensity to destroy temporaries too early (immediately after
function calls), the behavior is silently undefined; the code may pass
unittests.
Wouldn't the new runtime check fix this?
Depends how you define "fix". It would be a possibly rare bounds check
violation on completely innocuous code.
This is a known issue in C++. Allowing loose binding of rvalues to ref
not only inherits C++'s mistake, but also adds a fresh one.
I thought C++ would handle this kind of code. I remember being able to
use references to rvalues in ways that were unintuitive, but not undefined.
template <class T> const T& min(const T& a, const T& b) {
return b < a ? b : a;
}
...
int x = ...;
auto & weird = min(x, 100);
Have a nice day :o).
Andrei