0

Assumed I have following static variable within a method:

void myClass::myFct()
{
   static int myvar=0;

   ...
}

The behaviour is clear, "myvar" is initialised only once and whenever it is changed during "..." on next call of myFct(), the last value of myvar can be seen but not the initial value.

Now my question: what happens when the class "myClass" is deleted and then created again? Does this affect "myvar" (means is it initialised again) or is it left untouched and also after deletion/construction of the parent class the last (modified) value can be seen there?

Thanks!

Elmi
  • 5,899
  • 15
  • 72
  • 143
  • 1
    you can think of `static` variables as global ones with restricted visibiliy. This should be self explanatory – bartop Apr 16 '19 at 07:13
  • You mean an **instance** of the class is deleted and created again? – P.W Apr 16 '19 at 07:13

1 Answers1

5

what happens when the class "myClass" is deleted and then created again?

Nothing that changes myvar. It is left untouched. Note that this behavior is crucial: local, static data in a member function can't be tied to a particular class instance. Imagine multiple threads creating different instances of myClass, deleting it from time to time... how unpredictable and non-thread-safe would the behavior be if every deletion/creation causes a read to that variable?

lubgr
  • 37,368
  • 3
  • 66
  • 117