Asking a const-related fix

bearophile bearophileHUGS at lycos.com
Mon Nov 7 04:59:08 PST 2011


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);
}


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

Bye,
bearophile


More information about the Digitalmars-d mailing list