I am reading the Wikipedia page about references.
It contains the following code:
int& preinc(int& x)
{
return ++x; // "return x++;" would have been wrong
}
preinc(y) = 5; // same as ++y, y = 5
I did try to compile using return x++; instead of return ++x;. As predicted, this led to the following error:
error: invalid initialization of non-const reference of type ‘int&’ from a temporary of type ‘int’
I don't understand this error. I have the vague intuition that the incrementation of x happens too late (i.e., after the function call of preinc is over). However, I don't see how this is a problem since the variable x never ceases to exist. Any explanation is welcome.
The cause of the error is that post increment x++ returns a temporary value, and this cannot be bound to a non-const lvalue reference. This is a simplified version of the same problem:
int i = 42;
int& j = i++; // Error: i++ returns temporary value, then increments i.
const int& k = i++; // OK, const reference can bind to temporary.
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