C++ – How const Reference and const Pointer Work

ccompiler

I read a post about how const storage works.

How does const storage work? (Item 2, Scott Myers Effective C++)

This says that each segment has separate section of write protected memory and const data goes there.

But what happens in case of references?
I want to understand three scenarios.

  1. Global const reference.
  2. const reference in method.
  3. const reference in a class.

And for that matter pointers, I mean even though pointer can be stored in some write protected section, then how different versions of consts maintained.

such as

char x = 'z';
//following can not change the data of x, but ptr itself can change.
const char* ptr = &x;
char y = '9';
ptr = &y;

above is allowed but following is not

char* const ptr1 = &x;
ptr1 = &y;

How this is handled?

Best Answer

There are two aspects to the const in C++:

  • logical constness: When you create a variable and point a const pointer or reference to it, the compiler simply checks that you don't modify the variable via the const pointer or reference, directly or indirectly. This constness can be cast away with a const_cast<>. As such, the following code is perfectly legal:

    char myString[] = "Hallo Welt!";    //copy the string into an array on the stack
    const char* constPtr = myString;
    const_cast<char*>(constPtr)[i] = 'e';    //perfectly legal
    
  • physical constness: When you create a variable in static storage that is const, you allow the compiler to put in into non-writable memory. It may do so, or it may not. As far as the standard is concerned, you are simply invoking undefined behavior if you cast away constness to modify such an object. This includes all string literals, so the following code may or may not work:

     const char* myString = "Hallo World!";
     const_cast<char*>(myString)[1] = 'e';     //Undefined behavior, modifying a const static object!