Program termination via std::exit or std::abort: what happens to destructors of automatic (stack) objects in C++?

Difficulty: Easy

Correct Answer: are not called

Explanation:


Introduction / Context:
Automatic objects normally have their destructors run when their scope ends. However, abnormal or immediate termination paths behave differently. This question targets the behavior of std::exit and std::abort with respect to stack unwinding.



Given Data / Assumptions:

  • Automatic storage duration objects reside on the stack.
  • std::exit performs normal termination without unwinding stack frames.
  • std::abort terminates the process immediately.



Concept / Approach:
When std::exit is called, stack unwinding does not occur, so destructors for automatic (block-scope) objects are not called. Registered atexit handlers run, and static-duration objects may be destroyed. std::abort is harsher: it terminates immediately and does not call destructors or atexit handlers. Therefore, for automatic objects, the correct answer is that destructors are not called.



Step-by-Step Solution:
1) Local object inside a function → normally destroyed at scope end.2) Call std::exit(n) inside the function → the function never returns; no stack unwinding → no local destructor calls.3) Call std::abort() → immediate termination; no destructors of any kind are run.4) Therefore: “are not called”.



Verification / Alternative check:
Insert logging in destructors; compare a normal return path vs. calling std::exit or std::abort to observe the difference.



Why Other Options Are Wrong:
are called/are created/are inherited: contradict termination semantics.Special-casing main(): termination behavior is not limited to main's locals; the rule concerns stack unwinding globally.



Common Pitfalls:
Relying on stack object destructors for critical cleanup during process termination; prefer RAII plus ensuring normal shutdown paths, or register handlers as appropriate.



Final Answer:
are not called


Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion