Will the old variables (global) be destroyed at the end of the program?

Possible duplicate:
Is C ++ a call to destructors for global and class static variables?

What is the time of life

  • global MyClass myclass;
  • global static MyClass myclass;
  • global const MyClass myclass;
  • global static const MyClass myclass;
  • local static MyClass myclass; function static MyClass myclass; when it was actually initialized
  • global static constexpr MyClass myclass; in c ++ 11

and especially whether they will be destroyed on the usual final target (i.e. main remains without errors)? Where the standard claims it.

I noticed that a private destructor prevents the creation of all of these variables. But if I remember correctly, somewhere it was explicitly mentioned that some static data can be placed in the section of static data and already loaded with pre-designed ones. This would mean for me that the destructor would not be called. And that will mean that I am allowed to define such a variable ...

0
source share
2 answers

Destructors for objects in a namespace or namespace scope are called when the control flow exits main() .

If the exception leaves main() , then the implementation determines whether the destructors of any objects are called. With modern compilers, destructors will not be called in this case to provide an easy inspection of the state of the program when an unhandled exception was sent. In early C ++ implementations, an exception mechanism based on setjmp / longjmp that would unwind the stack when looking for an exception handler and, therefore, call destructors even if no suitable exception handler was found.

If the application terminates using _exit() or _exit() or std::quick_exit() , destructors are not called.

+4
source

Destructors for objects with a static lifetime (all cases when you specify objects with a static lifetime, although I do not think that an object in constexpr can have a non-trivial destructor): exit() called from the inside, the objects were built in the reverse order.

Returning from main calls exit to call with the return value, so returning from main will cause these destructors to be called. Other means of terminating the program ( abort() , denial of approval, _exit() , etc.) will not be called destructors.

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

+5
source

All Articles