A slightly different example:
const int *global_ptr = 0; void bar(); void foo() { int x = 1; global_ptr = &x; bar(); std::cout << x << "\n"; }
The compiler cannot optimize the last line to use the value 1 , because for everything it knows, bar() takes the value global_ptr , converts it to int* and modifies x through it. It will be a bit of a risky coding, but dropping the const specifier and mutation is valid provided that the link is really changed, so the compiler must allow this.
But if x were marked as const , then it would be wrong for bar() to discard const and mutate, and so the optimizer may assume that x still stores the value 1 when it is printed.
Optimizers, of course, identify compile-time constants for this kind of optimization, so I wonβt be surprised if this changes the source code. What is the difference in performance, I do not know. It is not difficult to generate cases where the identification of a constant can, for example, replace the (expensive) division with some (cheaper) bit or allow expressions involving
x and many other constants that will be computed at compile time instead of runtime.
In addition, connection time optimization may include bar , in which case the link time optimizer can more carefully check its contents and may be able to exclude its modification x even in non-const.
In your example, however, a link to colors may escape to an unknown code, so the difference does not occur. Anyway, a constant string is probably harder to optimize than const int, so there is even less chance that you will allow brilliant optimization with const .
Steve jessop
source share