2

So for code like this:

class foo{
  void bar(){
     static int var = 2;
  }
};

I know that there will only be on instance of var for all objects of type foo but does C++ allocate memory for variable var even before foo is created? I ask this because even after foo has been destroyed, var will exist throughout the program.

Samer
  • 1,923
  • 3
  • 34
  • 54
furssher
  • 83
  • 8

2 Answers2

5

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • *before* the first call to `foo::bar()`? What if the initial value had side-effects? (allowed in C++, not in C) Do those side effects occur at an unpredictable time? – Ben Voigt Sep 11 '14 at 21:01
  • Memory allocation is not initialization. *Initialization* (of the previously allocated memory area) will happen exactly the first time the function is called. It should be noted that the memory will be allocated statically at program startup, not using `malloc` or the like. – 5gon12eder Sep 11 '14 at 21:09
  • @BenVoigt Ah, these pesky side effects! Thanks! – Sergey Kalinichenko Sep 11 '14 at 21:16
3

var will be constructed the first time foo:bar() is called. It will be destructed when the program terminates.

Note that foo is a class, not an object instance, hence foo is never "destroyed"

UPDATE: The standard says that that the storage for the variable is allocated when the program begins. en.cppreference.com/w/cpp/language/storage_duration – (Thanks to broncoAbierto for correcting me).

James Curran
  • 101,701
  • 37
  • 181
  • 258