[Exceptional C++ Style] Exceptional C++ Style - Item 24: Constant Optimization

David Nash David.Nash at WallStreetSystems.com
Mon Jan 24 06:41:49 EST 2005


In this item, Herb raises the question of whether using constant references
for the the argument and return types of a function can allow the compiler
to perform some useful optimization, based somehow on the knowledge that the
values are constant.

The Guru question continues this by applying the same question to the use of
"const" generally within a function.

In both cases the answer is no.  The compiler cannot usefully optimize code
that uses const-qualified values because it cannot be sure that the values
are really and truly constant.

In the case of the argument and return values, the objects being passed are
both passed by reference, so can already avoid overhead from copying,
irrespective of whether they are const-qualified.  Both are also necessarily
defined out of the scope of the function in question so we don't know
whether they are really constant at all (IMHO they are likely not to be.
How many times do you pass a function a const reference to a non-const
string, for example?)

In the general case,  we still can't assume that a const object is really
constant.  For example, a member function of a const X may use const_cast to
modify a data member, or it may directly modify a member declared as
"mutable", two things that Herb describes as morally equivalent.

Also, we don't know whether some other code has a pointer to X, through
which it can call non-const functions or modify X directly.

The only way using "const" can help the compiler, is when defining something
const.  Then it could potentially be put into read-only memory.  Personally
I'm dubious even about this - const_cast (or plain old "C"-style cast) can
still be used in this case.

Finally, Herb reveals how const really can allow some optimization.  There
is in fact one, very specific, set of circumstances in which the compiler
might be able to use const-ness to generate better code.  This would be if
the definitions for all of const object Z's functions used in our function f
are visible, and those functions are all "pretty simple and free of side
effects".

It does turn out that "const" can allow the programmer to optimize, rather
than the compiler, for example by using a reference-counted handle/body
implementation you can avoid a deep copy when passing a Z to f, because you
know that  body part of Z is not going to change in f.  But as Herb points
out, simply passing Z to f by const reference  would avoid the copy too,
even for simple (not handle/body or ref-counted).

The guideline for this item is therefore: Avoid passing by const value -
prefer const reference instead, even for cheap-to-copy objects like ints.

In summary: Const is there to help us programmers, not the compiler.




More information about the Effective-cpp mailing list