The most obvious point where const is direct optimization is passing arguments to a function. It is often important to ensure that the function does not modify the data, so the only real choices for the function signature are as follows:
void f(Type dont_modify);
Of course, the real magic here passes the link, rather than creating a (expensive) copy of the object. But if the link was not marked as const , this will weaken the semantics of this function and will have negative effects (for example, more complex error tracking). Therefore const allows us to optimize here.
/ EDIT: in fact, a good compiler can analyze the control flow of a function, determine that it does not change the argument and does not optimize (by passing a link, not a copy). const here is just help for the compiler. However, since C ++ has rather complicated semantics, and such control flow analysis can be very expensive for large functions, we probably should not rely on compilers for this. Does anyone have data to support me / prove that I'm wrong?
/ EDIT2: and yes, as soon as custom copy constructors come into play, it becomes even more complicated, because compilers, unfortunately, are not allowed to skip them in this situation.
Konrad Rudolph Oct 17 '08 at 14:58 2008-10-17 14:58
source share