In the C++ primer, I found that const int &
can bind with a int object.I don\'t understand that,because I think const int &
should bind with a
In C++, you can refer to non-const objects with references and/or pointers to const.
int x = 10;
const int& r = x; //OK
const int* p = &x; //OK
Of course, since x is not constant it can be changed. However, what you're basically saying by having a const reference to a non-const object is: I will not change this object via this reference/pointer. You still can change the object directly or through other references or pointers.
Think of it as a read-only handle. Yes, the object itself may be mutable, but in many cases you may be willing to acquire and/or provide only a read-only access to that otherwise mutable variable.
Basically, const int & r
promises not to mutate the value it's referencing. This is a stronger guarantee than int &
. So, it's possible to refer to an int
using a const int &
reference. But you may not modify it. It's a subset of the operations possible on the value. However, it's not true the other way around, if you were trying to get a int &
reference to an const int
value, it would result in a compiler error because the value itself is immutable, and you are trying to get a mutable reference to this immutable value. The operations possible on the int &
reference are a superset of what's possible on const int
value.