Static variables in instance methods

前端 未结 5 1643

Let\'s say I have this program:

class Foo {
 public:
    unsigned int bar () {
        static unsigned int counter = 0;
        return counter++;
    }
};

int m         


        
相关标签:
5条回答
  • 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.

    0 讨论(0)
  • 2021-02-14 03:35

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

    0 讨论(0)
  • 2021-02-14 03:39

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

    0 讨论(0)
  • 2021-02-14 03:39

    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.

    0 讨论(0)
  • 2021-02-14 03:55

    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.
    0 讨论(0)
提交回复
热议问题