class A{
const size_t number;
public:
A(size_t number): number(number) {}
void f(){
//read number, possibly save in CPU register
//call a function that the compiler can't inspect
// so it should assume that anything in the program state changed
//read number again
}
There, where it reads the number again, will the compiler (if optimization is on) still assume that it cannot have changed, because it’s const, and so read the flag from the CPU register, if it was placed in one of them before?
The answer is that It depends on the implementation detail of the particular compiler.
Primary purpose of const correctness is to prevent yourself from making honest mistakes and writing more intuitive code which is easy to maintain.
Compiler optimization should (almost)never be a criteria for making something
const.A good compiler might apply its optimizations and inline the
constvariable, others may not.Some factors like if the address of the
constvariable is taken somewhere might also effect the way in how the compiler handles it.Last and most important regardless of how the compiler handles it once you declare a variable
const, your code should always assume that it is const, it should never be modified, modifying it with any hackery will cause an Undefined Behavior.