Question

Possible Duplicate:
Does C++ call destructors for global and class static variables?

What is the lifetime of

  • global MyClass myclass;
  • global static MyClass myclass;
  • global const MyClass myclass;
  • global static const MyClass myclass;
  • function local static MyClass myclass; when its initialization actually occured
  • global static constexpr MyClass myclass; in C++11

and especially will they be destroyed on regular program end (i.e. main is left without an error)? Where does the standard states so.

I noticed that a private destructor prevents the creation of all those variables. But if I remember correctly it was explicitly mentioned somewhere that some static data may be put into a static data section and loaded pre-constructed, already. This would imply for me that no destructor would be called. And this would imply I am allowed to define such a variable...

Was it helpful?

Solution

The destructors of file or namespace scope objects get called when the control flow leaves main().

If an exception leaves main() then it's implementation defined whether the destructors of any objects get called. With modern compilers the destructors won't be called in this case to allow easy inspection of the program state when the unhandled exception was thrown. Early C++ implementations used exception mechanism based on setjmp/longjmp which would unwind the stack while searching for the exception handler and hence calling destructors even if no suitable exception handler was eventually found.

If an application terminates with _exit() or _Exit() or std::quick_exit() no destructors get called.

OTHER TIPS

The destructors for objects with static lifetime (all of the cases you mention define objects with static lifetime—although I don't think that an object in a constexpr can have a non-trivial destructor) are called from within exit(), in the reverse order the objects were constructed.

Returning from main causes exit to be called with the return value, so returning from main will cause these destructors to be called. Other means of program termination (abort(), assertion failure, _exit(), etc.) will not call destructors.

If the objects are in a DLL (.so under Unix), the destructors will normally be called when the DLL is unloaded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top