In C++, when are global (namespace-scope, static-duration) objects destroyed?
-
AWhen the program terminates.
-
BWhen the control comes out of the block in which they are being used.
-
CWhen the control comes out of the function in which they are being used.
-
DAs soon as local objects die.
-
EImmediately after main() starts
Answer
Correct Answer: When the program terminates.
Explanation
Introduction / Context:Objects in C++ have lifetimes determined by their storage duration. Global objects (including namespace-scope statics) have static storage duration, meaning they exist for the entire run of the program. This question targets their destruction moment.
Given Data / Assumptions:
- Objects are defined at namespace scope or as static-duration items.
- Program startup initializes these objects before main begins (in a well-defined order per translation unit rules).
- We examine when their destructors run.
Concept / Approach:Static-duration objects are constructed before main() begins (after dynamic initialization) and are destroyed during program termination, after main() returns or std::exit is called, in the reverse order of construction within a translation unit. Destruction order across translation units follows implementation-defined rules but still occurs at program shutdown.
Step-by-Step Solution:1) Identify an object with static storage: global T g; or static T s;2) Program starts → dynamic initialization occurs → objects become live.3) Program terminates normally → destructors for these objects are invoked.4) Order is reverse of construction for the same translation unit.
Verification / Alternative check:Instrument constructors and destructors of global objects; you will observe construction before main() and destruction after main() ends.
Why Other Options Are Wrong:Block/function exit: those apply to automatic storage, not static-duration objects.“As soon as local objects die” or “immediately after main() starts”: contradict static lifetime semantics.
Common Pitfalls:Relying on a specific cross-translation-unit destruction order; use the “construct on first use” idiom or dependency-breaking techniques where order matters.
Final Answer:When the program terminates.