From 5.2.1.1:
The expression
E1[E2]is identical (by definition) to*((E1)+(E2))[...] except that in the case of an array operand, the result is an lvalue if that operand is an lvalue and an xvalue otherwise.
However, with the code below:
struct S { int arr[5]; }; int main() { int &&r = S().arr[0]; } both GCC and Clang complain about "rvalue reference cannot bind to lvalue int".
What have I misunderstood? As I understand S() is rvalue, S().arr is xvalue, so S().arr[0] should be xvalue as well and should be able to bind to rvalue refs.
for(auto &&r : c)pattern that also works forstd::vector<bool>. Edit: it does indeed.arr[0]returns a reference and the value is an array element, of an array which is a member variable of a temporary. So in this caserabsolutely does dangle, just not for the reasons originally mentioned. So OP: while this is a compiler bug, this code is still a terrible idea.rwould prolong the lifetime ofS(): "The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference"Sis never assigned to a reference, so why would its lifetime be extended? Working example (had to change to const ref, because coliru's clang/gcc versions have the bug): coliru.stacked-crooked.com/a/c8f585b116449088.