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()
?
This is because non-static members must belong to a class object, and static member functions have no class object to work with! Static member functions can also be defined outside of the class declaration. This works the same way as for normal member functions.
A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class.
From outside the class, "static variables should be accessed by calling with class name." From the inside, the class qualification is inferred by the compiler.
As static variables are initialized only once and are shared by all objects of a class, the static variables are never initialized by a constructor. Instead, the static variable should be explicitly initialized outside the class only once using the scope resolution operator (::).
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With