Question

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?

Was it helpful?

Solution

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 :).

OTHER TIPS

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).

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:

  1. Static variables are stored in static area of the executing program (which is same as that of global variable).
  2. Scope is limited by the general rules of parentheses.Additionally static variables have internal linkage.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top