any news on const/invariant?

Bruce Adams tortoise_74 at yeah.who.co.uk
Thu Nov 29 16:16:28 PST 2007


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) {

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.

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.

Regards,

Bruce.



More information about the Digitalmars-d mailing list