is my code to get CTFE instantiated object valid D ?

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 28 22:35:33 PDT 2016


On Saturday, 28 May 2016 at 15:39:44 UTC, ag0aep6g wrote:
> On 05/28/2016 10:34 AM, Mike Parker wrote:
>> On Saturday, 28 May 2016 at 05:30:26 UTC, chmike wrote:
> [...]
>>> Is a static const Category c variable a TLS variable ?
>>
>> Yes. All variables are TLS unless explicitly marked with 
>> __gshared or
>> shared.
>
> I don't think that's true.

> Prints (for example):
> ----
> 7F554F9E1710 695FF0 695FF4
> 7F554EDDA5D0 695FF0 695FF4
> ----
>
> So there are two different `m`s, but the `c`s and `i`s have the 
> same address on both threads. Seems to me that `m` is in TLS, 
> but `c` and `i` are not.

Well then, this completely breaks my understanding of variable 
scope. Consider this:

------
class Foo {
     int x;
     this(int i) { x = i; }
}

class Bar {
     static const Foo f;
     static this() {
         __gshared static firstRun = true;
         f = new Foo(firstRun ? 10 : 20);
         firstRun = false;

         import std.stdio;
         writeln("static con");
     }
}

void main() {
     import core.thread;
     print();
     new Thread(&print).start();
     Thread.sleep(1.seconds);
     print();

}

void print() {
     import std.stdio;
     writefln("Bar.f.x = %s, &Bar.f = %s", Bar.f.x, &Bar.f);
}
----

The static constructor is run per thread. The second iteration 
reinitializes the const reference 'f' with a new instance. Not at 
all what I would expect. IMO, either its a bug that there is only 
one instance of 'f', or it's a bug that it can be reinitialized.


More information about the Digitalmars-d-learn mailing list