any news on const/invariant?

Bill Baxter dnewsgroup at billbaxter.com
Thu Nov 29 16:42:27 PST 2007


Bruce Adams wrote:
> On Thu, 29 Nov 2007 04:53:43 -0000, Bill Baxter 
> <dnewsgroup at billbaxter.com> wrote:
> 
>> Walter Bright wrote:
>>> Bill Baxter wrote:
>>>> Here's a class that compiles fine and will probably mostly work.
>>>>
>>>> class Klass {
>>>>
>>>>     this() {
>>>>         array.length = 10;
>>>>     }
>>>>     const int elem(int i) {
>>>>         return array[i];
>>>>     }
>>>>
>>>>     int[] array;
>>>> }
>>>>
>>>> But someday when someone tries to call elem() with a const Klass it 
>>>> will fail to compile.
>>>  Yes. So where's the problem? Also, why would one want to return a 
>>> "const  int"? It doesn't make much sense.
>>
>> Doh.  Good point.  It doesn't make much sense returning a const int.
>>
>> I started with the function "const int*elem()", found out that didn't 
>> compile, and tweaked it so it would compile.  But I forgot to double 
>> check that the resulting code still made sense.  :-o
>>
>> --bb
> 
> 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) {

Oh, yeh, I do vaguely remember that one.  Good point.
Also for opIndex it can be used to prevent people thinking they're 
modifying the array when they're not:

struct FakeArray {
     int opIndex(int i) { return i*i; }
}

FakeArray x;
x[4]; //ok
x[4]++; // oops, only increments a tmp! probably not what you meant!

whereas if it returns a 'const int' the compiler will tell you you're an 
idiot.

> Personally I prefer to use lint to disallow assignment in boolean 
> expressions.
> 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.

I don't see much point in decorating all your value parameters with it. 
  But I've seen code written in that style.  All it does is promise to 
the caller that the function won't modify something that the caller 
can't see anyway.  Why do that?

> By the way to the const(this) advocates. Though the idea looks nice on 
> the surface
> it isn't quite consistent. const works on type (declarations), this is a 
> variable not
> a type.

Ok.  Let's make it "const(typeof(this))" then. :-)

Actually that's why I kind of preferred my "const()" suggestion.  It's 
applying const to the 'this' parameter which of course you can't see, 
because it's implicit.

--bb



More information about the Digitalmars-d mailing list