How can a C ++ or Java compiler make sure that none of the states of member variables is changed in a member function const(mutable exception).
const
Will the compiler do something like putting code in an unwritable code segment or something like that?
The compiler does not guarantee. It cannot, because there is no rule in the language that says that the state of a member variable cannot change in function const. The only rule: you cannot change state with a pointer this(without dropping const).
this
++ const . , const, - . , - .
Java , const.
++ , - ( , ) const ( ). . ( ) - , .
Java.
++: const this const- . .
ADD:
, const- this , const, .
++: , non-const - ( ). = .. " const... T... ... T...".
, const_cast.
const_cast
, , . , :
class A { public: // stuff... // int* getPointer() const {return mpA;} private: int* mpA; }
, mpA , ... mpA ( getPointer), mpA . , .
++ const . , const- ( ) .
, , , void foo(int) std::string , .
void foo(int)
std::string
, , , .
++ , const_cast ... :
, (, ,...) const, , const_cast Undefined .
, . const- . const int a = 10;, a = 20, , .