Constants and compiler optimization in C++

I think that the const keyword was primarily introduced for compilation checking of the program semantic, not for optimization.

Herb Sutter, in the GotW #81 article, explains very well why the compiler can’t optimize anything when passing parameters by const reference, or when declaring const return value. The reason is that the compiler has no way to be sure that the object referenced won’t be changed, even if declared const : one could use a const_cast, or some other code can have a non-const reference on the same object.

However, quoting Herb Sutter’s article :

There is [only] one case where saying
“const” can really mean something, and
that is when objects are made const at
the point they are defined. In that
case, the compiler can often
successfully put such “really const”
objects into read-only memory[…].

There is a lot more in this article, so I encourage you reading it: you’ll have a better understanding of constant optimization after that.

Leave a Comment