Let’s say I have this program:
class Foo {
public:
unsigned int bar () {
static unsigned int counter = 0;
return counter++;
}
};
int main ()
{
Foo a;
Foo b;
}
(Of course this example makes no sense since I’d obviously declare “counter” as a private attribute, but it’s just to illustrate the problem).
I’d like to know how C++ behaves in this kind of situation: will the variable “counter” in the bar() method be the same for every instance?
Yes,
counterwill be shared across all instances of objects of typeFooin 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 :).