class X{
public:
X(){}
};
class Y{
public:
Y(X x) { std::cout << "Temporary created!"; }
};
int main(){
X x;
const Y& y = x;
return 0;
}
Why does temporary object (of type Y
) get created here? I understand the necessity of a temporary object in this case, but I don't understand what the standard says about it. If we take a look at the standard, the only case which would fit our case here would be binding a reference to a prvalue, if I'm not mistaken. So does the subexpression x
in const Y& y = x
get converted to a prvalue or something else is happening here?
I've also taken a look at lvalue -> rvalue conversion, but the whole thing seems poorly explained. It doesn't say anything about the scenarios in which would this type of conversion occur. As far as I can tell, this conversion happens more often than I thought. For example, if we would take a look at implicit conversions on cpp.reference, almost every section starts with "A prvalue of an XXX type can be converted to YYY..." which indicates that most of the time in implicit conversions we use the lvalue->rvalue conversion as some kind of a base conversion. Closely related, I've also taken a look at this topic which could be a nice take on the whole situation, but also could be rather outdated.
So basically, I've got two questions. The first one from the title and (possibly not related) the second one: When does lvalue -> rvalue conversion actually occur ?
EDIT: regarding my first question (from the title) I've developed a theory which I believe fits with the draft. Basically, the expression x
gets converted to a prvalue of type const Y
, but without creating any objects. After that, we have a binding to prvalue which induces temporary materialization converting prvalue to xvalue. Only then we're binding a const
reference to that temporary object. How far am I from the truth?
Y
object doesy
refer to when I doconst Y& y = x;
?x
is not aY
, soy
cannot be referring to it. – Hankyx
inconst Y& y = x
gets converted to a prvalue or something else is happening here? Have you followed the links from "the standard"? (e.g. eel.is/c++draft/dcl.init.ref) – Drumstick