Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "static this()" outside of a class mean?

Tags:

d

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() ?

like image 441
Arlen Avatar asked Jun 02 '11 05:06

Arlen


People also ask

Why static methods should be defined outside the class?

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.

Can static variable be used outside a class?

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.

Can we use static variables outside the class in Java?

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.

Can we declare static variable outside the class in C++?

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 (::).


2 Answers

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.

like image 169
Peter Alexander Avatar answered Sep 18 '22 09:09

Peter Alexander


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).

like image 25
vines Avatar answered Sep 21 '22 09:09

vines