Let\'s say I have this program:
class Foo {
public:
unsigned int bar () {
static unsigned int counter = 0;
return counter++;
}
};
int m
By "be the same for every instance" you mean there will be one instance of this variable shared across each class instance, then yes, that's correct. All instances of the class will use that same variable instance.
But keep in mind that with class variables you have to take things like multi-threading into account in many cases, which is a whole different topic.
From The C++ Programming Language (2nd edition), page 200, by Bjarne Stroustrup:
Don't use static except inside [plain] functions (§7.1.2) and classes (§10.2.4).
Yes, counter
will be shared across all instances of objects of type Foo
in your executable. As long as you're in a singlethreaded environment, it'll work as expected as a shared counter.
In a multithreaded environment, you'll have interesting race conditions to debug :).
Your example was a couple lines away from being something you could compile and test:
#include <iostream>
using namespace std;
class Foo {
public:
unsigned int bar () {
static unsigned int counter = 0;
return counter++;
}
};
int main ()
{
Foo a;
Foo b;
for (int i=0; i < 10; i++)
cout<<i<<". "<<a.bar()<<" / "<<b.bar()<<endl;
}
The output looks like this:
0. 1 / 0
1. 3 / 2
2. 5 / 4
3. 7 / 6
4. 9 / 8
5. 11 / 10
6. 13 / 12
7. 15 / 14
8. 17 / 16
9. 19 / 18
So yes, the counter is shared across all instances.
You just need to grasp two things: