any news on const/invariant?

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


Bill Baxter wrote:
> 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.

My bad, the compiler actually catches that.  But it doesn't catch it if 
you make opIndex return a struct with an opPostInc.

And ooh another D2 bug: actually making it return a const(Strukt) 
crashes the compiler.

--bb



More information about the Digitalmars-d mailing list