does C++ allocate memory for variable var
even before foo is created?
Yes, it does, in the sense that the memory the value of var
will eventually occupy is reserved upfront. When the constant value of 2
is written into var
's memory is implementation-defined. The only thing the standard guarantees is that it is going to happen at some point before you call foo::bar()
.
If you initialize your static variable using an expression with side effects (say, by making a function call) this call will be performed the first time that you execute the function.
after foo has been destroyed, var will exist throughout the program.
var
will exist independently of any instances of foo
that your program may create. When you call foo::bar()
at any time, you would get the last value of var
that your program has assigned to it.