const again

Sean Kelly sean at f4.ca
Thu Dec 6 14:21:45 PST 2007


Walter Bright wrote:
> As a result of all the const comments here, and some serious semantic 
> problems discovered (dang it's hard to think of everything in advance), 
> it seems there needs to be another tweak of the const behavior.
> 
> Every time we try to sneak in "tail-const" in some form, some semantic 
> correctness breaks somewhere. For example, struct member functions can 
> be const or non-const, but there is no notion of "tail-const" for struct 
> member functions. Trying to accommodate this results in all kinds of 
> peculiar rules and inconsistencies.
> 
> The second thing that just causes endless difficulties is the idea of 
> using const to declare manifest constants, as in:
>     const x = 3;
> having the same meaning as the C:
>     #define x 3
> in that 1) x does not consume storage and 2) x is typed as int, not 
> const(int). For example,
>     auto i = x;
> one would *not* want i to be typed as const(int).

Makes sense.

> So, we're going to try a new, simpler regime:
>     const T x;
> is semantically identical to:
>     const(T) x;
> and the type of x is const(T).
> 
> That leaves what to do about manifest constants. It occurs that we 
> already have a mechanism for them - enums. So why not:
>     enum x = 3;
>     enum long y = 4;
> ? I think that solves our problem.

One thing that concerns me.  If we assume that "enum x = 3" is simply 
shorthand for "enum { x = 3 }" then all such declarations would be 
implicitly typed as integers, which doesn't sound like you want.  It 
seems you're suggesting "enum" be treated more like a storage class 
here?  I'm not sure if I like that idea.

> There's one last problem:
>     class C { }
>     const(C)[] a;
>     a[3] = new C();  // error, x[3] is const

As I see it, an array of objects can have two levels of const-ness:

1. The array itself is const and may not be resized or have its contents 
changed.
2. The array is not const but its elements are, so the array may be 
resized, but only const member functions may be called on the contained 
objects.

To me, "const(C)[]" looks like case 2, because only the element type is 
in parenthesis.  Thus "const C[]" or "const (C[])" would both represent 
case 1.  However, this is obviously not how things currently work.  I 
this has something to do with the desire to shoehorn tail const into the 
design, but it doesn't feel natural to me.  Can you explain why it works 
the way it does?


Sean



More information about the Digitalmars-d mailing list