Alex Rivera | Logout

When are static C++ class members initialized?

Asked 2009-09-14T13:51:15.380
80

There appears to be no easy answer to this, but are there any assumptions that can be safely made about when a static class field can be accessed?

EDIT: The only safe assumption seems to be that all statics are initialized before the program commences (call to main). So, as long as I don't reference statics from other static initialization code, I should have nothing to worry about?

Edit
Report

1 Answer

-1

i think the main thread of a proccess will execute the following five steps in order

  1. initialization of CRT library

  2. static initialization

  3. execution of main() function

  4. static unitialization

  5. unitialization of CRT library

you want reference statics from other static initialization code? maybe the following codes work:

class A;
static auto_ptr<A> a(auto_ptr<A>(&GetStaticA()));
A &GetStaticA(void)
{
    static A *a = NULL; //the static basic type variables initialized with constant experession will be initialized earlier than the other static ones
    if (a == NULL)
    {
         a = new A();
         return *a;
    }
}
answered 2009-09-14T14:57:41.197

Your Answer