Why is it not allowed to get non-const reference to a temporary object,
which function getx()
returns? Clearly, this is prohibited by C++ Standard
but I am interested in the purpose of such restriction, not a reference to the standard.
struct X
{
X& ref() { return *this; }
};
X getx() { return X();}
void g(X & x) {}
int f()
{
const X& x = getx(); // OK
X& x = getx(); // error
X& x = getx().ref(); // OK
g(getx()); //error
g(getx().ref()); //OK
return 0;
}
- It is clear that the lifetime of the object cannot be the cause, because constant reference to an object is not prohibited by C++ Standard.
- It is clear that the temporary object is not constant in the sample above, because calls to non-constant functions are permitted. For instance,
ref()
could modify the temporary object. - In addition,
ref()
allows you to fool the compiler and get a link to this temporary object and that solves our problem.
In addition:
They say "assigning a temporary object to the const reference extends the lifetime of this object" and " Nothing is said about non-const references though". My additional question. Does following assignment extend the lifetime of temporary object?
X& x = getx().ref(); // OK