The keyword static
unfortunately has a few different unrelated meanings in C++
When used for data members it means that the data is allocated in the class and not in instances.
When used for data inside a function it means that the data is allocated statically, initialized the first time the block is entered and lasts until the program quits. Also the variable is visible only inside the function. This special feature of local statics is often used to implement lazy construction of singletons.
When used at a compilation unit level (module) it means that the variable is like a global (i.e. allocated and initialized before main
is run and destroyed after main
exits) but that the variable will not be accessible or visible in other compilation units.
I added some emphasis on the part that is most important for each use. Use (3) is somewhat discouraged in favor of unnamed namespaces that also allows for un-exported class declarations.
In your code the static
keyword is used with the meaning number 2 and has nothing to do with classes or instances... it's a variable of the function and there will be only one copy of it.
As correctly iammilind said however there could have been multiple instances of that variable if the function was a template function (because in that case indeed the function itself can be present in many different copies in the program). Even in that case of course classes and instances are irrelevant... see following example:
#include <stdio.h>
template<int num>
void bar()
{
static int baz;
printf("bar<%i>::baz = %i\n", num, baz++);
}
int main()
{
bar<1>(); // Output will be 0
bar<2>(); // Output will be 0
bar<3>(); // Output will be 0
bar<1>(); // Output will be 1
bar<2>(); // Output will be 1
bar<3>(); // Output will be 1
bar<1>(); // Output will be 2
bar<2>(); // Output will be 2
bar<3>(); // Output will be 2
return 0;
}
static int i
specific to the instance, so that e.g.o1.foo(); // i = 1
and$o2.foo(); // i = 1
...? – Beaton