My code does not compile.
int foobar()
{
// code
return 5;
}
int main()
{
int &p = foobar(); // error
// code
const int& x = foobar(); //compiles
}
Why does adding the keyword const make the code compile?
In C++ temporaries cannot be bound to non-constant references.
In
int &p = foobar();
The rvalue expression foobar()
generates a temporary which cannot be bound to p
because it is a non-const reference.
const int &x = foobar();
Attaching the temporary to x
which is a reference to const prolongs its lifetime. It is perfectly legal.
Because foobar()
is returning by value; this result is a temporary. You cannot have a non-constant reference of a temporary.
If this were not true, what would this code do?
int &x = foobar();
x = 1; // Where are we writing to?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With