Reputation: 6835
I'm very well aware of static constructors, but what does it mean to have a static this()
outside of a class?
import std.stdio;
static this(){
int x = 0;
}
int main(){
writeln(x); // error
return 0;
}
And how do I access the variables define in static this()
?
Upvotes: 11
Views: 1600
Reputation: 54290
It's a module constructor. That code is run once for each thread (including the main thread).
There are also module destructors as well as shared module constructors and destructors:
static this()
{
writeln("This is run on the creation of each thread.");
}
static ~this()
{
writeln("This is run on the destruction of each thread.");
}
shared static this()
{
writeln("This is run once at the start of the program.");
}
shared static ~this()
{
writeln("This is run once at the end of the program.");
}
The purpose of these is basically to initialise and deinitialise global variables.
Upvotes: 17
Reputation: 5225
This is the module constructor. You can read about them here: http://www.digitalmars.com/d/2.0/module.html
Obviously, you can't access x
in your sample, because it's a module constructor's local variable, just as well as you couldn't have done it with a class constructor's one. But you can access module-scope globals there (and initialise them, which is what the module constructors are for).
Upvotes: 14