struct A {
int &r;
A (int &i) : r(i) {}
void foo () const {
r = 5; // <--- ok
}
};
The compiler doesn’t generate any error at r = 5;.
Does it mean that &r is already const-correct being a reference (logical equivalent of int* const) ? [Here is one related question.]
I’m not sure exactly what you mean by “already const-correct”, but:
Assigning to
ris the same as assigning to whatever thing was passed into the constructor ofA. You’re not modifying anything in the instance ofAwhen you do this, so the fact thatfoois declared const isn’t an obstacle. It’s very much as if you’d done this:The fact that
foois const means that it doesn’t modify anything in theAinstance it’s called on. There’s no conflict between that and having it modify other data it was supplied with.Of course if you happened to arrange for
rto be a reference to some member ofAthen callingfoowould modify the instance ofAafter all. The compiler can’t catch all possible ways in whichconstness of a member function might be violated; when you declare a member functionconstyou’re promising that it doesn’t engage in any such subterfuge.