static variable inside member function of base class

前端 未结 2 1947
再見小時候
再見小時候 2021-01-23 18:17

i have the following:

   class base
   {
      public
       void f();
       ...
   }
    void base::f()
    {
        static bool indicator=false;
         ...         


        
相关标签:
2条回答
  • 2021-01-23 19:01

    Static variables declared in member functions will keep their value between function calls. There will be only one copy over all instances, and all accesses to indicator from different instances will affect the same indicator. This means indicator will only be initialized once.

    See here for more info: Static variables in member functions

    Also this code does not toggle indicator, it always sets it to true if it's false (which I'm sure is the behaviour you want).

    if(!indicator)
         {
            ...
            indicator=true;
          }
    
    0 讨论(0)
  • 2021-01-23 19:06

    This is precisely the behavior of static variables declared inside function blocks. It has been like that since the introduction of the feature in the C programming language.

    The static declaration can also be applied to internal variables. Internal static variables are local to a particular function just as automatic variables are, but unlike automatics, they remain in existence rather than coming and going each time the function is activated. (K&R, page 61).

    The static initializer is executed before the first invocation of the containing function. Being static, the variable retains its last state across the invocations.

    0 讨论(0)
提交回复
热议问题