[Exceptional C++ Style] Exceptional C++ Style - Item 24: Cons tantOptimization

Ric Parkin ric.parkin at ntlworld.com
Thu Jan 27 06:33:08 EST 2005


From: "Hammond, Peter" <peter.hammond at amsjv.com>
> > An old guideline said const  (non-ref) params belong to the 
> > *impelmentation 
> > details*. So in headers and function interfaces const shall 
> > be omitted (it's 
> > discarded by the compiler anyway). And the implementation can 
> > insert cont at 
> > will if it feels like it.
> > 
> 
> I was wondering about this in the context of coding standards recently. In
> Exceptional C++ (item 43) Herb remarks that const on a value parameter is
> pointless, and when I see it in a header it worries me: it is a sign that
> someone may have misunderstood const, or pass-by-vlaue, or both. 

There's one other reason, which I'll come onto later.

> On the
> other hand, having the constness of the argument enforced in the
> implementaion can be very useful. The obvious way to solve it is to leave it
> in the implemtation, but remove it from the definition, as the guideline
> above. However, the difference between declaration and definition would seem
> to be a source of confusion for many. Has anyone got any experience of this
> kind of guideline and whether in practice it helps or confuses?

It's not as bad as you might think, as people rarely look at *both* declaration and definition at the same time.

And when they do, it doesn't take long to explain what's going on. Especially if your shop has guidelines like "make local variables const if possible" and "never modify a parameter"*.

The main problem I've seen is that some code *tools* (including some versions of popular IDEs - not sure if fixed recently) get confused between the two and think that they are different definitions. Usually a minor inconvienience though, and can be got around by putting the const in the declaration too.

As for does it help - a bit more than routinely declaring local variables as const if possible, but still not massive. 

It can help a little to catch changing values during maintenence - it can be tempting to "just reuse this variable" and this helps resist such potentially dangerous (and usually confusing) habits.

Ric
* as in if an int is passed in, don't change it. And don't change a pointer either, but you can change what is pointed at, so in/out and out parameters work.


-----------------------------------------
Email provided by http://www.ntlhome.com/





More information about the Effective-cpp mailing list