Suppose to have the code
#include <iostream>
struct A{
int y;
int& x;
A():y(0),x(y){}
};
void f(int& x){
x++;
}
void g(const A& a){
f(a.x);
//f(a.y);
}
int main(){
A a;
g(a);
std::cout<<a.y<<std::endl;
}
inside g()
calling f() on y is not allowed because a is passed with the const modifier
however, the value of y can be modified inside g() by calling f on x;
With pointers, a similar things can be obtained very similarly
struct B{
int* x;
}
and
g(const B&){
*x++;
}
is allowed. This is perfectly clear: We have a const pointer to non-const int.
But in the previous reference example, if references ARE the object, why do in this case they behave as pointers? What are the design policies under this behavior?
The actual language in the standard is
So if a reference is a name of an object, not an object itself, then it makes sense that causing the enclosing structure to be
constmakes the nameconst(which is meaningless, as references can’t be rebound), but not the object itself.We also see
Since member access on a cv object creates a cv lvalue, the same applies and the cv qualification is extinguished.