www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - About static variables

reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
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. :)
Sep 02 2011
parent travert phare.normalesup.org (Christophe) writes:
Nothing worth adding a confusing semantic to the langage. Just prefix 
your variable's name.
Nobody will want to use myFunctionPrivateVariable outside of myFunction:

class Foo {
  private size_t myFunctionPrivateCount;
  void myFunction() {
    alias myFunctionPrivateCount count;
       // ..
       count++;
  }                                                                            
                                                                             
}
Sep 05 2011