Given the following:
struct S
{
int x;
int& y;
};
int main()
{
int i = 6;
const S s{5, i}; // (1)
// s.x = 10; // (2)
s.y = 99; // (3)
}
Why is (3) allowed when s is const?
(2) produces a compiler error, which is expected. I'd expect (3) to result in a compiler error as well.
CodePudding user response:
Why is
s.y = 99allowed whensisconst?
The type of s.y for const S s is not int const& but int&. It is not a reference to a const int, but a const reference to an int. Of course, all references are constant, you cannot rebind a reference.
What if you wanted a type S' for which const object cannot be used to change the value y refers to? You cannot do it simply, and must resort to accessors, or any non-const function (e.g. operator=):
class U
{
int& _y;
public:
int x;
void setY(int y) { _y = y; } // cannot be called on const U
};
