Reputation: 8126
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?
Upvotes: 1
Views: 1135
Reputation: 341
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.
Upvotes: 7