And as I understand it, the compiler is allowed to assume that r is not
changed inside f1 when optimizing code that calls f1. So for example:
void foo() {
const int r = 12;
f1(r);
int w = r; // the compiler is allowed to assign the
// value 12 to w here. Even though f1 changed r.
Walter Bright has posted a number of informative posts over the
years regarding this exact (incorrect) assumption. Here are the
general points:
1) it is legal to cast away const from a reference so a const &
is of little use to the compiler for optimization.
2) given 1) the compiler must analyze the code independent of
const & declarations.
3) the compiler can only sometimes determine legal optimizations
in the presence of references/pointers due to aliasing problems
etc. In the limited example above (with only that one reference)
it /would/ be able to do such optimizations but they would happen
regardless of the const qualifier.
4) top level const /is/ useful for optimization since it is UB to
modified a const objects (excepting mutable sub-objects). The most
common example are simple file or namespace scope constants such as:
int const TheBufferSize = 2048 ;
As to the topic of the thread, Leigh has already posted (twice)
the correct answer. Since many of you probably missed it due to
killfile filtering I've copied it below:
It is UB if the actual object that r refers to is const.
KHD