Static variable inside a method


Hi

This is more like a performance evaluation.

I hav a static integer variable 'count' inside a method of class a, in order to keep track of no.of times this method was called.

and class a is contained in class b.

there could be huge number of class b objects existing in the application.

so is it really a good idea to declare the variable count as static inside that method?

how could the compiler differentiate count variable for different objects?

any suggestion is appreciated.

--
how could the compiler differentiate count variable for different objects?
It can't. Local static variables have nearly the same semantics as global variables. The only difference is that they can't be used by other functions, and that they are constructed when their functions are first called (if a function that contains a static is never call, that static is never constructed).

Local static variables have nearly the same semantics as global variables.


does it mean that it maintains a single static variable for all the objects?
Yes.
Opinions differ, but when I need to use static variables, I try to go from less visibility (fewer dependencies) to more:

1. static variable inside a method/function (C-style)
2. static variable in a module (.cpp) - doesn't show up in .hpp so less dependency between modules (C-style)
3. static variable in a class (C++-style)

The general idea is, you want to limit the scope of that static (global) variable as much as possible.
If you are writing multithreading code, you want to avoid static variables as much as possible.
+1 kfmfe04

That goes for all variables of all types.
Topic archived. No new replies allowed.