“静态this()”在一个类之外是什么意思?

时间:2011-06-02 05:09:44

标签: d

我非常清楚静态构造函数,但在类之外有static this()是什么意思?

import std.stdio;

static this(){

  int x = 0;

}


int main(){

  writeln(x); // error

  return 0;
}

如何访问static this()中定义的变量?

2 个答案:

答案 0 :(得分:16)

这是一个模块构造函数。该代码为每个线程(包括主线程)运行一次。

还有模块析构函数以及共享模块构造函数和析构函数:

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.");
}

这些的目的基本上是初始化和取消初始化全局变量。

答案 1 :(得分:14)

这是模块构造函数。你可以在这里阅读它们:http://www.digitalmars.com/d/2.0/module.html

显然,您无法访问示例中的x,因为它是模块构造函数的局部变量,就像您不能使用类构造函数的那样完成它。但是你可以在那里访问模块范围的全局变量(并初始化它们,这是模块构造函数的用途)。