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.
- Global const reference.
- const reference in method.
- 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 theconst
pointer or reference, directly or indirectly. This constness can be cast away with aconst_cast<>
. As such, the following code is 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: