[comp.lang.c++] experience using const

roger@procase.UUCP (Roger H. Scott) (08/12/90)

In article 8285, <10329@cadillac.CAD.MCC.COM>, vaughan@mcc.com (Paul Vaughan)
writes:
>...
>Does anyone have any experience, intuition, or statistics concerning
>the use of const?  Does it really help clear up errors or not?  It's
>certainly a bag of worms to get a program const correct--it just
>ripples and ripples through your code and then you wind up finding a
>place in some library or system function where something really should
>have been const but can't be changed and you have to cast around it in
>the end.  So what's the verdict is const worth it?

When I was at Data General we made an effort to make our programs "const
correct".  We were using cfront 1.1 at the time, so one of the first things
we discovered was that without const member functions you don't stand a
chance of controlling who's modifying what objects.  Consequently we were
one of the loudest agitators for const member functions and stringent object
const-ness checking by the compiler.  You are absolutely right that const-ness
(when retrofitted) ripples through your code in an amazing manner.  We didn't
accept your limitation that some code "can't be changed" - we made our
header files "correct" w.r.t. const-ness.  As has been noted in previous
discussions of const, a tricky business is the distinction between const
concrete state (what the compiler implements) and const abstract state (what
the programmer typically has in mind).  I found myself casting "this" to
a non-const pointer in a number of places so that "theoretically" const
member functions could modify the internal state of objects.
As far as the "value" of const, my impression was that the exercise of
going through and making as much stuff const as possible significantly
increases one's understanding of the code involved, and often results in
"beneficial" restructuring so as to reduce the number of places and ways
that state is modified.  My experience in software engineering is that most
bugs stem from code incorrectly or inconsistently modifying state, so it
seems reasonable to conclude that, all told, greater use of const can lead
to significantly better software.