How it is useful to create a static variable in a non static member function? The compiler allows that, and i wonder in what situations it is useful to create static variables in the function bodies as they are going to be disposed at the end of the function call.
I don't agree. I think that they have a place in modern code.
I have a few situtation that I think merit them. (as will all good things, go easy on them, even in my biggest code bases, there may only be 10 of them).
Let us consider a function in a geometric matrix class, that say gets a point P and finds the appropiate cell which P exists in, and returns that integer.
That function requires a bit of optimization (particularly for non-orthoganal/non-space-filling cells) and it is found that about 50% of the time the cell is the same as the last search. (P didn't move much). So add a static variable to the method, and record the cell found.
Why not add it as a class static variable? Well that adds a level of scope pollution. Why have a variable in the class, and have to have initializers etc, have someone inadvertently change it. It is a similar argument to declaring variables local to the method, in the class.
you simple would not do it, so I don't see how it is different for a static variable.
I fully agree that if the optimization starts getting a bit more sophisticated, the static variable might need to go to the class level, or be registered to an instance of the class etc, or become a complex monster :)
I also like them when some resource is required on something since the static variable in only initialized on first call to the function, but class static variables are initialized before a call to main.
p.s. N.B there are not static constants, there are constants or static. (if it is constant you don't need static)
If a non-static variable is required, it is either local to the method or local to the class. Fine, no problem 99% of variables are just that.
But when a static variable is required, then that is completely different. This way ALL calls to the method regardless of instance have the same static variable. That is typical for specialization of event type in a monte-carlo, base-class has getCell and specialization class knows about the event that can take place, the new energy/velocity of the particle.