Static variables in instance methods

前端 未结 5 1727

Let\'s say I have this program:

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

int m         


        
5条回答
  •  不要未来只要你来
    2021-02-14 03:31

    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.

提交回复
热议问题