About static variables

Andrej Mitrovic andrej.mitrovich at gmail.com
Fri Sep 2 16:06:41 PDT 2011


There's no question here but just an observation. I've recently had
this sort of bug:

class Foo {
   void test() {
       static size_t count;
       // ..
       count++;
   }
}

void main() {
    auto foo1 = new Foo;
    foo1.test();
    auto foo2 = new Foo;
    foo2.test();  // affects the same static count variable
}

count was initially a field of Foo and as such had separate instances
for every class instantiation. I've made it a static variable to hide
it from other class functions because I only really need it inside of
one function as a count variable. But I've introduced a bug, because
count became a static variable that is *shared* between class
instances.

If I spawn a new thread, then that thread gets its own instance of the
static variable. E.g. if you run the following, you'll see that the
threads don't stomp on each other and each has their own static
variable:

http://codepad.org/qf1Tf8j9

Of course you can mark the static variable shared and count will be
one variable shared for all instances of the class in any thread.
Anyway..

I like creating self-contained functions that don't rely on too much
external state (even if it's class state). I kind of wish I could
create instance-local static variables inside virtual functions. Of
course that's exactly what field variables are for, but then other
functions have access to those field variables when they don't really
need to.

That's all. :)


More information about the Digitalmars-d-learn mailing list