Static variables in instance methods

前端 未结 5 1665

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

提交回复
热议问题