How should the compiler make sure that the state of the data member does not change in the const function? (either in C ++ or in Java)

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).

Will the compiler do something like putting code in an unwritable code segment or something like that?

+5
source share
7 answers

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).

+3

++ const . , const, - . , - .

Java , const.

+3

++ , - ( , ) const ( ). . ( ) - , .

Java.

+1

++: const this const- . .

ADD:

, const- this , const, .

0

++: , non-const - ( ). = .. " const... T... ... T...".

, const_cast.

, , . , :

class A
{
public:
  // stuff...
  //
  int* getPointer() const {return mpA;}
private:
  int* mpA;
}

, mpA , ... mpA ( getPointer), mpA . , .

0

++ const . , const- ( ) .

, , , void foo(int) std::string , .

, , , .

++ , const_cast ... :

, (, ,...) const, , const_cast Undefined .

0

, . const- . const int a = 10;, a = 20, , .

0

All Articles