I get how. I don't get why. (more const stuff)

Steven Schveighoffer schveiguy at yahoo.com
Fri Sep 7 09:12:16 PDT 2007


"Janice Caron" wrote in message
> It just seems to me that, had it been defined differently - for example, 
> suppose that "const(T) x" meant that x was immutable, and that anything 
> referenced by x (transitively) was also immutable, then it all would have 
> made sense. There would have been no need for "const T x" to even exist, 
> and there would have been no reason for "const(T) x" to behave differently 
> depending on whether T is a class or a struct. As you say, there probably 
> were good reasons for not doing that, but I'm blowed if I can see what 
> they are.

I think the main confusion comes from the fact that a class reference is a 
pointer, even though it doesn't have a * in the definition.  If you think of 
it this way, i.e.:

const(classref) means that the classref itself is not const, but the thing 
it points to is.  There is an implied * after the closing ')'
const(structtype) * means that the structtype pointer itself is not const, 
but the thing that it points to is.

const(structtype) means that the structtype itself is not const, and you 
just wasted 7 perfectly good keystrokes typing 'const()' around it since the 
structtype doesn't point anywhere.  This makes no sense to me either...

I agree that it is confusing, and I too would like to hear reasons why it is 
this way.  To me, if you have something that looks like f(x), then x should 
be defined in terms of f, not f(x) * means the * outside the parentheses 
should be defined in terms of f, but because x is in the parentheses, it is 
excluded from the effects of f ???  This goes against my hard-wired 
mathematical brain...

Although it isn't intuitive, the definition needs to be complete for the 
third example above.  My first vote is to change the syntax.  maybe 
something like (warning, new keyword ahead):

pconst reftype x -> x is not const, but the referenced data is
pconst valuetype * x -> x is not const, but the referenced data is
pconst valuetype x -> compiler error, pconst cannot be applied to 
non-pointer types.
const reftype x -> x and the referenced type are both const
const ptrtype x -> x and the referenced type are both const
const valuetype x -> x is const.

That not being acceptable, my second vote is for const(valuetype) x 
generating a compiler error, as the current behavior is definitely not what 
the author intended.  I think this would make the definition complete, even 
if it is counter-intuitive.

-Steve 





More information about the Digitalmars-d mailing list