Asking a const-related fix

Steven Schveighoffer schveiguy at yahoo.com
Mon Nov 7 05:06:38 PST 2011


On Mon, 07 Nov 2011 07:59:08 -0500, bearophile <bearophileHUGS at lycos.com>  
wrote:

> Jonathan M Davis:
>
>> The errors that you're running into are completely by design.
>
> I see, thank you for your (and Steven's) answers.
>
> Isn't it possible to see unassigned constant array attributes as mutable  
> just inside their struct/class constructor (and allow the code I've  
> shown)? It's handy because often I just need to initialize them in the  
> constructor, and later I don't need to change them any more.
>
> -------------------------
>
> Steven Schveighoffer:
>
>> Line 8 is invalid, because a const member is only allowed to be
>> initialized *once* in a constructor.
>
> Is this a DMD bug then (this compiles and runs)?
>
>
> const struct Foo {
>     const int y;
>     this(in int x) pure {
>         y = x;
>         y = x + x;
>     }
> }
> void main() {
>     auto f = Foo(5);
> }

I would say yes, though I supposed the compiler may be able to take leeway  
and prove that the y = x line is not needed.

If it compiles at all, I think it would be implementation defined.

>
>
> In the following program Foo1 and Foo2 are not allowed, while Foo3 is  
> allowed. Is this a good design? They seem similar enough cases to me.
>
>
> const struct Foo1 {
>     const int[1] a;
>     this(in int x) pure {
>         a[0] = x; // Error
>     }
> }
> const struct Foo2 {
>     const int[1] a;
>     this(in int x) pure {
>         a = [x]; // Error
>     }
> }
> const struct Foo3 {
>     const int a;
>     this(in int x) pure {
>         a = x; // OK
>     }
> }
> void main() {}

I agree all of these should be valid.  I think the ever-impressive Kenji  
Hara is working on that case.

-Steve


More information about the Digitalmars-d mailing list