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.

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
@BenVoigt Ah, these pesky side effects! Thanks!
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).

6 Comments

foo is never “destroyed” but its static members are as part of the program de-initialization. For an int, this is of course a no-op.
@5gon12eder: yes, but the OP referred to the destruction of foo as something happening before shutdown.
The standard says that that the storage for the variable is allocated when the program begins. en.cppreference.com/w/cpp/language/storage_duration
@broncoAbierto: That's why I hedged on it. Thanks. I'll update it.
@broncoAbierto: That website says it. But what does the standard say?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.