偶尔看到D语言有些代码里会出现 static this() {},若是是在类里好理解,静态构造函数。可是放到模块里,我就纳闷了,不知道具体起什么做用了。看了渡世白玉(http://www.dushibaiyu.com/)的代码,算是有点理解:
app.dhtml
import std.stdio; import std.concurrency; import core.thread; void fun() { writeln("fun run in thread :", Thread.getThis().id); } void spawnfun() { writeln("spawnfun run in thread :", Thread.getThis().id); } void main() { writeln("main in thread :", Thread.getThis().id); spawn(&spawnfun); auto th = new Thread(&fun); th.start(); }
a.d
app
module a; import core.thread; import std.stdio; static this() { writeln("A static this in thread :", Thread.getThis().id); } shared static this() { writeln("A shared static this in thread :", Thread.getThis().id); }
运行结果以下:函数
官网解释以下:
https://dlang.org/spec/module.html学习
Static constructors are code that gets executed to initialize a module or a class before the main() function gets called. Static destructors are code that gets executed after the main() function returns, and are normally used for releasing system resources.this
There can be multiple static constructors and static destructors within one module. The static constructors are run in lexical order, the static destructors are run in reverse lexical order.spa
Static constructors and static destructors run on thread local data, and are run whenever threads are created or destroyed.code
Shared static constructors and shared static destructors are run on global shared data, and constructors are run once on program startup and destructors are run once on program termination.orm
具体应用场景还没想到,等有空了继续 学习,先忙工做了。htm