简体   繁体   中英

Modifying reference member from const member function in C++

I am working on const-correctness of my code and just wondered why this code compiles:

class X
{
    int x;
    int& y;
public:
    X(int& _y):y(_y)
    {
    }
void f(int& newY) const
    {
        //x = 3; would not work, that's fine
        y = newY; //does compile. Why?
    }
};

int main(int argc, char **argv) 
{
    int i1=0, i2=0;
    X myX(i1);
    myX.f(i2);
...
}

As far as I understand, f() is changing the object myX, although it says to be const. How can I ensure my compiler complains when I do assign to y? (Visual C++ 2008)

Thank a lot!

Because you are not changing any variable in X . Actually, you are changing _y which is an outsider with respect to your class. Don't forget that:

y = newY;

Is assigning the value of newY to the variable pointed by y , but not the references them selves. Only on initialization the references are considered.

The situation is similar to pointer members. In a const member function, the const applies to the pointer itself, not the pointee.

It's the difference between:

X* const //this is how the const applies: you can modify the pointee
const X*

Except X& const isn't valid syntax, since the reference can't be made to refer to another object in the first place (they are implicitly always const). In conclusion: const on methods has no effect on member references.

As additional information for the accepted answer, I want to say, in fact one can change variables in X.

Because you are not changing any variable in X.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Bar {
public:
    void funcA() const {
        c++;
    }

    int b = 3;
    int &c = b;
};

int main()
{
    Bar b;
    b.funcA();
    cout << b.b << endl;  //4
}

So the main idea for this problem is:

It modifies what the member refers to, it does not modify the member.

This also applies for pointer members.

See here Why can reference members be modified by const member functions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM