immutable ctors, immutable members, and TDPL

TommiT tommitissari at hotmail.com
Fri May 24 03:06:50 PDT 2013


On Friday, 24 May 2013 at 08:47:40 UTC, Dicebot wrote:
> Also one issue Don has brought my attention to is this snippet:
>
> // -----------------------------
>
> immutable int x = 1;
>
> void main()
> {
> 	import std.stdio;
> 	writeln(x);
> }
>
> static this()
> {
> 	x = 42;
> }
> // (does not compile in 2.062 and won't in 2.063)
>
> // ------------------------------
>
> Whatever approach is taken, I think it should be consistent 
> with structs/classes in a sense that global variables are 
> module members and module constructor is, well, constructor.
>
> But it looks very hard to do because "immutable" is implicitly 
> "shared". Ideas?

That shouldn't compile because the non-shared module constructor 
writes to the shared variable x whenever a new thread starts with 
that module.

But a better question is whether or not it should compile with a 
shared module constructor:

immutable int x = 1;

shared static this()
{
     x = 42;
}

... I don't know, but I think it should follow the same logic as 
with a non-static immutable member variable and a shared default 
constructor.

Also, I think the following shouldn't compile due to a non-shared 
module constructor assigning to a shared variable (currently it 
does compile):

immutable int x;

static this()
{
     import std.random;
     x = uniform(0, 100);
}


More information about the Digitalmars-d mailing list