I came to know that S{}.rval
is an lvalue expression. I want to know the rationale behind considering it an lvalue expression.
Why are access to non-static member of reference type lvalue, even when the object is an rvalue?
struct S {
int val;
int& rval = val;
};
int main() {
S{}.val; // xvalue
S{}.rval; // lvalue
}
My expectation would have been that a reference to a "soon to die entity" would also be "soon to die". So I'd like to understand the rationale of the rule(s).
My expectation would have been that a reference to a "soon to die entity" would also be "soon to die".
That is not always true. The reference member may alias an object that will outlive the temporary S{}
.
For example:
int i = 10;
struct S {
int& rval = i; // rval refers to the global i
};
int main() {
S{}.rval; //the aliased object will outlive the object expression `S{}`
}