any news on const/invariant?
Bruce Adams
tortoise_74 at yeah.who.co.uk
Mon Dec 17 11:16:34 PST 2007
On Mon, 17 Dec 2007 16:12:05 -0000, James Dennett <jdennett at acm.org> 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).
>
In actual fact when I sat down to check it and prove the point either way
I discovered that gcc in every case I could think of produces a is not an
l-value syntax error.
> (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.
>
> -- James
You misread me. I am strongly in favour of const-correctness. My point was
about const on value returns, which do not contribute to const correctness.
const is about the interface contract for a function. There is no
difference
between const valueType1 foobar(const valueType1)
and valueType1 foobar(valueType2)
valueType1 is not an l-value and therefore not assignable etc.
valueType2 the situation is not quite the same but I would contend that..
Whether or not valueType2 is modified by foobar is an implementation
detail and should
not be part of the contract.
You can just as easily say in the body:
foobar(valueType2 bar)
{
const valueType2 IamConst = bar;
... use IamConst
}
or
foobar(const valueType2)
{
valueType2 IamNotConst = bar;
... use IamNotConst
}
constness helps a little here but it affects the implementation only.
Ideally I'd like the to be able to declare constness of an argument in
the implementation but leave it out of the declaration. Implementation in
the compiler
wise it would be trivial but syntactically its hard to think of something
appropriate.
In D this is even weirder because you don't have separate declarations and
implementations.
More information about the Digitalmars-d
mailing list