我非常了解静态构造函数,但是static this()在类之外有什么意义呢?
import std.stdio;
static this(){
int x = 0;
}
int main(){
writeln(x); // error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我如何访问定义的变量static this()?
Pet*_*der 17
它是一个模块构造函数.该代码为每个线程(包括主线程)运行一次.
还有模块析构函数以及共享模块构造函数和析构函数:
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.");
}
Run Code Online (Sandbox Code Playgroud)
这些的目的基本上是初始化和取消初始化全局变量.
vin*_*nes 14
这是模块构造函数.你可以在这里阅读它们:http://www.digitalmars.com/d/2.0/module.html
显然,你无法访问x你的样本,因为它是一个模块构造函数的局部变量,就像你不能用类构造函数那样做.但是你可以在那里访问模块范围的全局变量(并初始化它们,这是模块构造函数的用途).