reference field are writable even when host object is const

In the example below, the intVar field is a nonref and behaves as expected — can't be modified via a const method, and can't be modified via a variable marked const.

However the reference field this->intRef is not on the real estate of the host object and isn't part of the host object state, so in both cases above intRef is modifiable!

using namespace std;
template struct J{
    J(T & rhs):intRef(rhs){}
    void doIt(T a) const{
        this->intRef = a; // legal even when method is const and is called !
        //this->intVar = a; // illegal when method is const and is called
    T & intRef;
    T intVar;
int main()
    int a=22;
    const J j1(a);
    j1.intRef = 19; // legal even when object is const
    //j1.intVar = 19; // illegal when object is const


Fill in your details below or click an icon to log in: 徽标

您正在使用您的 账号评论。 登出 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 登出 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 登出 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 登出 /  更改 )

Connecting to %s