any news on const/invariant?

James Dennett jdennett at acm.org
Tue Dec 18 22:43:29 PST 2007


Bill Baxter wrote:
> James Dennett wrote:
>> Bruce Adams wrote:
>>
>> [snip]
>>
>>> I personally agree that const on value types in C++ is a stupid idea.
>>> Meyers recommends it (effective C++) for the following case however:
>>>
>>> T operator*(T,T)
>>>
>>> if ((a*b)=c)) { //oops!
>>>
>>> instead of:
>>>
>>> if ((a*b)==c) {
>>>
>>> Personally I prefer to use lint to disallow assignment in boolean
>>> expressions.
>>
>> A good compiler can do that for you too (though using lint
>> is a fine idea to supplement even a good compiler).
>>
>> (Scott's advice here doesn't suit me; "do as the ints do" is
>>
>>> There is a school that uses const value types even for builtins like
>>> int.
>>> I am currently trying to convince people at work that it is pointless
>>> and neither
>>> being const correct not just a style thing.
>>
>> It's not pointless, and it's not just a style thing.  It avoids
>> defects, and it makes code clearer for those who are used to
>> both styles.  Maybe instead of setting out to convince people of
>> something, you could set out to discover which solution really
>> works better in practice.  Using const has known advantages in
>> expressiveness and defect elimination; apart from saving
>> typing, what's the benefit of *not* recording the design
>> decision that some value will not change during execution?
>> It's a very lightweight, compile-time enforced invariant check.
> 
> I can't speak for all the cases the original poster was talking about,
> but const on value parameters is useless excess verbiage in my opinion.
> 
> float sin(const float) { ... }
> 
> Here I'm recording my design decision that my implementation of sin will
> not change its copy of the float argument passed in.
> 
> Great.  Callers just don't care.  Such uses of const clutter up the
> interface for no good reason in my opinion.  Most other uses of const on
> simple value types I'm ok with.

And you're close to the crucial point.  For C++, it makes sense to
write a function *definition* with top-level const as above, to avoid
typos in the function which accidentally modify its copy of the
argument.  It means *nothing* to the caller, so the function's
declaration (which is part of its interface) need not (and, for
style reasons, should not) include the const -- in a non-definition,
top-level const is a meaningless comment, and the compiler ignores
it.

-- James



More information about the Digitalmars-d mailing list