Can static variables in methods be local for each object?

Dukc ajieskola at gmail.com
Tue Jul 20 15:59:30 UTC 2021


On Tuesday, 20 July 2021 at 09:24:07 UTC, Mark Lagodych wrote:
> Is there a way to make myvar local to each instance of `X` 
> without making it a variable of `X`? Just curious.

Yes.

```d
import std.stdio;

class X {
     int x(int param) {
         static int[typeof(this)] myvar;

         if (param == 0) return myvar.get(this, 1234);
         else return myvar[this] = param;
     }

}

void main()
{
     X x1 = new X;
     X x2 = new X;

     x1.x(0).writeln; //1234
     x2.x(0).writeln; //1234

     x1.x(17).writeln; //17
     x2.x(0).writeln; //1234

     x1.x(0).writeln; //17
     x2.x(0).writeln; //1234
}
```

However, this is definitely not recommended. When you are calling 
a function with any particular object and argument set, you want 
it to do the same thing and return the same result, regardless of 
what's called before. Otherwise you're making debugging much more 
difficult than it needs to be.

This means that `static` variables should generally be used only 
for two things:
1: data that is only set at the beginning of the program, or at 
first use, and then left to the initial value.
2: caching results of expensive computation. Even this is a bit 
controversal, as it's easy to screw up - often it's just better 
to split the function in two, and let the caller to cache the 
results.

In this case, consider passing `myvar` explicitly:

```d
import std.stdio;

class X {
     int x(int param, ref int[typeof(this)] myvar) {
         if (param == 0) return myvar.get(this, 1234);
         else return myvar[this] = param;
     }

}

void main()
{
     X x1 = new X;
     X x2 = new X;
     int[X] myvar;

     x1.x(17, myvar).writeln; //17
     x2.x(0, myvar).writeln; //1234

     x1.x(0, myvar).writeln; //17
     x2.x(0, myvar).writeln; //1234

     myvar = null; //Forget all calls made so far
     x1.x(0, myvar).writeln; //1234
     x2.x(0, myvar).writeln; //1234
}
```


More information about the Digitalmars-d-learn mailing list