This pointer is a rvalue. It cannot be assigned a value, so that this pointer is a const pointer does not matter.
If f()
is a non const member function, this pointer points to non const X
, so data member of X can be modified.
But if f() const
is a const member function, this pointer points to const const X
, so data member of X cannot be modified. Then, it need for data member to be mutable or to const_cast if one wants to modify it inside f() const
definition.
We can do, for const_cast,
void X::f() const{
const_cast <int&> (member) = 1;
}
If member
is a reference to a non-const int, then assignment is accepted by compiler and have wanted behavior. If member
is reference to a const int, behavior is not predictable. Compare these:
const int a = 10;
const int* b = &a;
int* c = const_cast<int*>(b);
// *c = 20;
c is a const_cast of a const int* whose pointee a is const. Behavior is undefined.
int a1 = 10;
const int* b1 = &a1;
int* c1 = const_cast<int*>(b1);
*c1 = 20;
c1 is a const_cast of a const int* whose pointee a is const. This is working, you can freely assign new value to int pointed by c1.
It is known that const member function cannot change value of data members. What we say her is that this is because then, this pointer's pointee is const.