From my understanding , mutable cancels the constness of a variable
Class A {
void foo() const {
m_a = 5;
}
mutable int m_a;
};
But also const_cast :
void print (char * str)
{
cout << str << endl;
}
int main () {
const char * c = "this is a line";
print ( const_cast<char *> (c) );
return 0;
}
So , what changes one from the other ?
Thanks
const_castcannot cancel constness of an object.const_castcan only remove constness from an access path to an object. Access path is a pointer or a reference to an object. Removing the constness from the access path has absolutely no effect on the object itself. Even if you useconst_castto remove the constness of the access path, that still does not necessarily give you the permission to modify the object. Whether you can do it or not still depends on the object itself. If it is const, you are not allowed to modify it and any attempts to do so will result in undefined behavior.For example, this illustrates the intended use of
const_castThe only reason the above is legal and valid is the fact that
iis actually a non-constant object, and we know about it.If the original object was really constant, then the above code would produce undefined behavior:
C++ language does not allow you to modify constant objects and
const_castis completely powerless here, regardless of how you use it.mutableis a completely different thing.mutablecreates a data filed that can be legally modified even if the containing object is declaredconst. In that sensemutabledoes allow you to modify [some designated parts of] constant objects.const_cast, on the other hand, can’t do anything like that.