Run-time initialised static variables
dekevin
dekevin at student.ethz.ch
Tue Feb 6 23:50:52 UTC 2018
On Tuesday, 6 February 2018 at 23:21:36 UTC, Jonathan M Davis
wrote:
> 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
Thanks a lot! I will change all my initialisations to static
constructors now.
The only additional problem I have, is that ℚInf has a disabled
default constructor.
Is there a way to allow shared static constructors, but not the
default constructor?
struct ℚInf {
ℚ qval;
immutable static ℚInf zero;
@disable this();
shared static this() {
zero.qval = ℚ(0);
}
this(long num, long den) {
qval = ℚ(num,den); //this initialisation requires
dynamically linked code
}
}
Best,
Kevin
More information about the Digitalmars-d-learn
mailing list