44

Possible Duplicate:
Will exit() or an exception prevent an end-of-scope destructor from being called?

In C++, when the application calls exit(3) are the destructors on the stack supposed to be run to unwind the stack?

3
  • And, is there an alternative approach? throw a special type instead of calling exit, catch it in main, and then return from main instead of exit from main? Commented Jun 11, 2016 at 18:10
  • 1
    @AaronMcDaid I don't understand your question. Alternative approach to what? What would you be trying to accomplish by avoiding a call to exit()? In one of my apps, I do throw an customExit object and catch it in main and use an integer value from the customExit object to supply the return value from main, this way my RAII destructors are run to clean up things like temporary files. Commented Jun 11, 2016 at 19:06
  • your comment answered my (badly written) question exactly. Thanks! Basically, I wanted confirmation that other people use this throw approach to ensure everything is destructed in a normal program exit Commented Jun 11, 2016 at 20:10

2 Answers 2

59

No, most destructors are not run on exit().

C++98 §18.3/8 discusses this.

Essentially, when exit is called static objects are destroyed, atexit handlers are executed, open C streams are flushed and closed, and files created by tmpfile are removed. Local automatic objects are not destroyed. I.e., no stack unwinding.

Calling abort lets even less happen: no cleanup whatsoever.

Sign up to request clarification or add additional context in comments.

1 Comment

For people who want no cleanup to happen, _exit() might be a better call than abort(), since abort will raise the SIGABRT signal, typically resulting in behavior quite similar to a crash.
10

If your OS is reasonable (Unix, Linux, or a recent Windows), calling exit() tells the kernel to de-allocate all the processes' memory. The stack doesn't need to be unwound; it will simply cease to exist.

1 Comment

And any RAII code in stack destructors will NOT be called. Which may not matter if it deals only with memory private to the process; but which matters if it deals with (a) files that need to be deleted or renamed,or otherwise cleaned up, and (b) the integrity of data structures shared between processes in shared memory. // For reasons such as these, some projects have forbidden the use of exit, and/or have redefined exit() to throw an exception that will cause stack unwinding.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.