Consider the following code:
int x;
int& f() {
return x ? x : throw 0;
}
With gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04)
I get the following compilation error:
cannot bind non-const lvalue reference of type ‘int&’ to an rvalue of type ‘int’
Note that this compiles just fine in clang. Here is (what I believe to be) the relevant statement from the standard:
N4659 [8.16.2.1] (Conditional Operator):
The second or the third operand (but not both) is a (possibly parenthesized) throw-expression (8.17); the result is of the type and value category of the other.
As far as I understand, x
is an lvalue, so it seems to me that clang
is right. Am I wrong?
If I had to take a guess, the l-to-rvalue conversion is occurring because the two expressions in the conditional don't have the same type, but because the second is a throw this conversion should be preempted. I'm not familiar with submitting bug reports, but perhaps that would be a better forum for this.
Here are some (probably) more helpful questions about the conditional operator:
Why does this function return an lvalue reference given rvalue arguments?
Error: lvalue required in this simple C code? (Ternary with assignment?)