Local static class fields

Bert Bert at gmail.com
Mon Aug 12 22:48:43 UTC 2019

Making a field static is effectively a global variable to the 

I have a recursive class structure(think of a graph or tree) and 
I need to keep a global state for it, but this state actually 
needs to be different for each tree object. The reason for this 
is that structurally it will not change per tree and if it it is 
not static then it wastes space unnecessarily.

class X
     X[] x;
     static State s;

making s non-static has the problem that every X will allocate 
storage for s wasting space since for any instance chain of X's 
they will all have the same s. Making it static though then makes 
it the same for all instance chain's of X, of which it should be 
local to each.

One way around this is to use an dictionary that associates each 
state to each instance chain.

That is there is a initial X that is the parent of the chain and 
we can then associate a state to it's address, any other chain 
will have a different initial X and so we can get a new state.

class X
     X[] x;
     static State[X] s;

This is not a huge difficulty to do but does require finding the 
initial X to use, which is not difficult but wastes cycles for 
large chains. There will, of course, be a constructor that 
constructs a chain and creates a new state for it and updates s.

Is there any way to do this more naturally in D?

More information about the Digitalmars-d-learn mailing list