1

When exactly the static members of a particular C++ class are created and destroyed? Let's say I have defined a WinVersion class:

WinVersion.h

class WinVersion {
public:
    // static methods
    static WinVersion& Get();
    static bool Is_NT();

    // singleton
    static WinVersion m_version;

    // constructor
    WinVersion();

private:
    unsigned short m_PlatformId;
    unsigned short m_MajorVersion;
    unsigned short m_MinorVersion;
    unsigned short m_BuildNumber;
};

WinVersion.cpp:

// static members
WinVersion WinVersion::m_version = WinVersion(); // unsure if it's good enough

// static functions
WinVersion& WinVersion::Get() {
    return m_version;
}

bool WinVersion::Is_NT() {
    return (m_version.m_PlatformId == VER_PLATFORM_WIN32_NT);
}

// constructor
WinVersion::WinVersion()
{
    OSVERSIONINFO osinfo;
    osinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    ...
}

When will m_version static member be created and destroyed? What happens in case of exceptions?

ezpresso
  • 7,896
  • 13
  • 62
  • 94
  • I think it's pretty safe to assume that your code is on Windows NT. – Puppy May 05 '12 at 16:49
  • *When will m_version static member be created and destroyed?* w.r.t or as compared to what? The order of initialization of static members is same as the order in which they are declared in the TU. Across the TU the order is not defined. – Alok Save May 05 '12 at 16:54
  • Possible duplicate: http://stackoverflow.com/q/1421671/777186 – jogojapan May 06 '12 at 00:21

1 Answers1

7

Static members are initialized before main(), and they are destroyed in reverse order of creation after the return in main().

Static members are statically allocated, and their lifetime begins and ends with the program.

Exceptions don't apply to static members initialization because you can't be there to catch any exceptions a static object will throw. You shouldn't "expect" there to be static member initialization problem before your program even begins, this is clearly an error.Your compiler and linker will let you know of any problems with static definitions.

Adam Dreaver
  • 341
  • 1
  • 7
  • 1
    It might be worth mentioning that the initialization of static members of class *template instances* (assuming that it falls into the dynamic initialization phase) is unspecified. Furthermore, the initialization order across multiple translation units is always unspecified. – Kerrek SB May 05 '12 at 17:54