Alex Rivera | Logout

What is the lifetime of class static variables in C++?

Asked 2009-07-03T14:31:48.967
15

If I have a class called Test ::

class Test
{
    static std::vector<int> staticVector;
};

when does staticVector get constructed and when does it get destructed ?

Is it with the instantiation of the first object of Test class, or just like regular static variables ?

Just to clarify, this question came to my mind after reading Concepts of Programming Languages (Sebesta Ch-5.4.3.1) and it says ::

Note that when the static modifier appears in the declaration of a variable in a class definition in C++, Java and C#, it has nothing to do with the lifetime of the variable. In that context, it means the variable is a class variable, rather than an instance variable. The multiple use of a reserved word can be confusing particularly to those learning the language.

did you understand? :(

Edit
Report

2 Answers

3

Simply speaking:
A static member variable is constructed when the global variables are constructed. The construction order of global variables is not defined, but it happens before the main-function is entered.

Destruction happens when global variables are destroyed.

Global variables are destroyed in the reversed order they were constructed; after exiting the main-function.

Regards,
Ovanes

P.S.: I suggest to take a look at C++-Standard, which explains (defines) how and when global or static member variables are constructed or destructed.

P.P.S.: Your code only declares a static member variable, but does not initialize it. To initialize it you must write in one of the compilation units:

std::vector Test::staticVector;
or
std::vector Test::staticVector=std::vector(/* ctor params here */);

answered 2009-07-03T15:07:52.860
1

Some specific VC++ information in case that's what you're using:

  1. Static class variables construction occurs at same time as other static/global variables.
  2. In windows, the CRT startup function is responsible for this construction. This is the actual entry point of most programs you compile (it is the function which calls your Main/Winmain function). In addition, it is responsible for initializing the entire C runtime support (for example you need it to use malloc).
  3. The order of construction is undefined, however when using the microsoft VC compiler the order of construction for basic types will be OK, for example it is legal and safe to write

statics.h: ... MyClass declaration ... static const int a; static int b; static int ar[]; } statics.cpp:

const int MyClass::a = 2;
int MyClass::b = a+3;
int MyClass::ar[a] = {1,2}
answered 2009-07-03T15:17:15.833

Your Answer