In http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ it mentions \"most important const\" where by C++ deliberately specifies that binding a
Note that const references can be bound to objects that don't even have an address normally. A const int &
function parameter can take an argument formed by the literal constant expression 42
. We cannot take the address of 42
, so we cannot pass it to a function that takes a const int *
.
const references are specially "blessed" to be able to bind to rvalues such as this.
Of course, for traditional rvalues like 2 + 2
, lifetime isn't an issue. It's an issue for rvalues of class type.
If the binding of a reference is allowed to some object which, unlike 42
, does not have a pervasive lifetime, that lifetime has to be extended, so that the reference remains sane throughout its scope.
It's not that the const causes a lifetime extension, it's that a non-const reference is not allowed. If that were allowed, it would also require a lifetime extension; there is no point in allowing some reference which then goes bad in some parts of its scope. That behavior undermines the concept that a reference is safer than a pointer.
Here's an example:
void square(int &x)
{
x = x * x;
}
int main()
{
float f = 3.0f;
square(f);
std::cout << f << '\n';
}
If temporaries could bind to non-const lvalue references, the above would happily compile, but produce rather surprising results (an output of 3
instead of 9
).
Consider the following:
int& x = 5;
x = 6;
What should happen if this was allowed? By contrast, if you did
const int& x = 5;
there would be no legal way to modify x
.