digitalmars.D.learn - About static variables
- Andrej Mitrovic (36/36) Sep 02 2011 There's no question here but just an observation. I've recently had
- travert phare.normalesup.org (Christophe) (11/11) Sep 05 2011 Nothing worth adding a confusing semantic to the langage. Just prefix
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
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