I encountered the following error while trying to use C++ reference with objects. After reference to this question, I understood that it's because A()
returns a temp variable, which is, by design, not allowed to be referenced to by a non-const reference
. However, I'm still curious about why C++ is designed in that way. Why couldn't A& ra2 = A();
serve as a shorthand for A a1 = A(); A& ra1 = a1;
? MSVC is known to support this kind of syntax by an extension, which nonetheless is not included in other implementations. Is there a particular downside of this shorthand?
class A {
public:
int a = 0;
};
int main()
{
A a1 = A();
A& ra1 = a1; //okay
A& ra2 = A(); //error: invalid initialization of non-const reference of type ‘A&’ from an rvalue of type ‘A’
return 0;
}