Run-time initialised static variables

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Feb 6 23:21:36 UTC 2018


On Tuesday, February 06, 2018 23:03:07 dekevin via Digitalmars-d-learn 
wrote:
> Hello everyone,
> I just ran into the problem, that I need a static variable, where
> the initialisation code for that variable is only accessible
> during run-time (since part of the initialisation code will be
> dynamically linked).
>
> Is there a way to do this in D?
>
> To be a bit more concrete, this is where I have the problem
> (where ℚ uses GMP, which is dynamically linked):
>
> struct ℚInf {
>     ℚ qval;
>     immutable static ℚInf zero = ℚInf(0,1);
>     this(long num, long den) {
>          qval = ℚ(num,den); //this initialisation requires
> dynamically linked code
>      }
> }

So, you want qval to be static and initialized at runtime? Then use a static
constructor. e.g.

struct QInf
{
    ...
    static this()
    {
        qval = ...;
    }
    ...
}

That doesn't work if you're dealing with a static local variable, but it
works for static members of structs and classes, and it works for
module-level variables.

And if you want to make qval immutable, then use a shared static
constructor. e.g.

struct QInf
{
    ...
    shared static this()
    {
        qval = ...;
    }
    ...
}

You can currently initialize immutable static variables with non-shared
static constructors, but that's a bug and will result in the immutable
variable being reinitialized whenever a new thread is created.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list