Static attributes aren' immutable

div0 div0 at
Fri Mar 5 06:45:08 PST 2010

Hash: SHA1

bearophile wrote:
> I'm playing some more with immutables in D2. This program compiles:
> struct Foo {
>     static int x;
> }
> void main() {
>     immutable Foo f;
>     Foo.x++;
>     f.x++;
> }
> Is this code supposed to be correct? If I have an immutable struct I want all of it to be immutable...
> Bye and thank you,
> bearophile

Yes it's correct.

x is really just a global variable, or a thread local variable if you
are using a newer compiler.

putting it in Foo simply puts it in a namespace.

You could argue that 'f.x++' should not be allowed
in order to emphasis that x is not part of an instance,
but that could make writing generic code more awkward.

IIRC, you can do:

immutable struct Foo {
    static int x;

Then you can't write to x, but then you can't ever
write to any instance members either.

- --
My enormous talent is exceeded only by my outrageous laziness.
Version: GnuPG v1.4.7 (MingW32)
Comment: Using GnuPG with Mozilla -


More information about the Digitalmars-d-learn mailing list