Home > Enterprise >  Non-const member reference is mutable on const object?
Non-const member reference is mutable on const object?

Time:12-05

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 = 99 allowed when s is const?

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
};
  • Related