33 CONST

CONST

Reference: CONST in c++

If you decalre something with const, you're saying that you are not going to modify that thing.

Combning with pointers

const int* a = new int;
// or 
int const* a = new int; 
// they mean that you can not modify the content of the memory address to which a pointed.

int* const a  = new int;
// it means that you can not modify what memory address a pointed to.

const int* const a = new int;
// both above can not

Read it backward, like the compiler does. For instance :

  • const int * A; ==> "A is a pointer to an int that is constant."
    (or, depending on how you prefer to write it)

  • int const* A; ==> "A is a pointer to a const int"

  • int * const A; ==> "A is a const pointer to an int."

  • const int* const A; ==> "A is a const pointer to an int that is constant".

Const int * A does not mean that A actually points to a const variable. It just means that the compiler will not allow you to modify the pointed value through A.

for instance :

int val = 10;
int const * a = &val;
*a = 30; //this will NOT compile, you're not allowed to modify "val" through "a".
val = 30; //this will compile. 

Same with :

int val = 10;
int val2 = 30;
const int * const A = &val; 

A = &val2; //will NOT compile : you can't modify what A points to.
*A = 30; //will NOT compile : you can't modify val through A

val = 30; //this will compile, val is not constant

Compiling things:

// the code
 const int MAX_AGE = 90;
 int* a = new int;
 a = (int*)&MAX_AGE;
 *a = 85;
 std::cout << *a << " " << MAX_AGE << std::endl;

// The output:  85 90

//I used the memory inspector in debug mode and saw the value pointed by &MAX_AGE actually being changed from 90 to 85 . So what the hell? Why is 90 the output for _MAX_AGE_, if the memory was actually modified!??

//I took one step further and inspected the generated .asm file (as taught by Cherno) to realize that the compiler optimized the code by replacing all read operations of MAX_AGE with the literal 90 . That cleared everything!! It's reasonable for a compiler to eliminate the need of accessing a variable if its never gonna change: just replace its occurrence with the said value from the get-go. One less operation each time it's used.

With classes and methods

class Entity
{
private:
  int m_X, m_Y;
  mutable int var; // even in a const decalred method, you can modify this variable
public:
  int GetX() const // const after the method name declares that it would not modify the class member.
  {
    var = 5; // you can modify it;
    return m_X;
  }
  
  int GetX()
  {
    m_X = 5;
    return m_X;
  }
};

void PrintEntity(const Entity& e)
{
  // const declare means that you can not modify the completely things of e, so if you call one method without const declared, you'll get an error
  std::cout << e.GetX() << std::endl;
}


int main()
{
  Entity e;
  
}
posted @ 2024-09-02 17:37  zhihh  阅读(23)  评论(0)    收藏  举报