In C++, which destructors and handlers run when a program calls std::exit instead of returning from main?
answer
- the current stack is abandoned
- statics and atexit, reverse order
- C streams flushed
- a local ofstream's buffer
basics
~20 sstd::exit destroys thread-local objects of the calling thread, then static objects interleaved in reverse order with atexit handlers, and flushes C streams, but it never destroys automatic objects on the stack. Returning from main also destroys main's locals first.
solid answer
~40 s`std::exit(status)` does not return and does not unwind. Its steps: destroy objects with thread storage duration of the current thread; destroy objects with static storage duration and call functions registered with `std::atexit`, in reverse order of their construction and registration; flush and close all C streams and remove `tmpfile` files; return the status. Objects with automatic storage duration, in every active stack frame, are not destroyed. So a `std::ofstream` local to the function that calls `std::exit` never runs its destructor, and whatever sits in its buffer can be lost, while `printf` output and a static logger survive. Returning from `main` differs only in destroying `main`'s own locals first. That is why a CLI build tool reports errors by returning from `main` rather than calling `std::exit` deep in the call stack.
code
cpp · 24 lines#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
struct Log {
const char* name;
~Log() { std::printf("~%s\n", name); }
};
Log global{"static"}; // static storage duration
int main(int argc, char** argv) {
std::atexit([] { std::printf("atexit handler\n"); });
std::at_quick_exit([] { std::printf("at_quick_exit handler\n"); });
Log local{"local"}; // automatic storage duration
std::printf("buffered line\n"); // sits in stdout's buffer when piped
const char* how = argc > 1 ? argv[1] : "return";
if (!std::strcmp(how, "exit")) std::exit(3);
if (!std::strcmp(how, "quick_exit")) std::quick_exit(4);
if (!std::strcmp(how, "abort")) std::abort();
if (!std::strcmp(how, "terminate")) std::terminate();
return 2;
}go deeper
Remember that std::exit ends the program immediately from where it is called, without destroying local variables.
List exit's steps: thread-locals, statics interleaved with atexit handlers in reverse order, C stream flush, and explain what returning from main adds.
Spot data loss from std::exit skipping RAII buffers and replace deep exit calls with an exception caught in main.
Set the rule that only main decides the exit status, so shutdown always runs destructors, and audit code paths that call std::exit.
## The sequence `std::exit` follows The C++ standard specifies `std::exit(int status)` as a fixed series of steps: 1. Objects with **thread storage duration** associated with the calling thread are destroyed. 2. Objects with **static storage duration** are destroyed and functions registered with **`std::atexit`** are called. The two are interleaved: in general, things constructed or registered later are destroyed or called earlier, according to the ordering rules for termination. 3. All open **C streams** with unwritten buffered data are flushed, all C streams are closed, and files created by `tmpfile()` are removed. 4. Control returns to the host environment with the status. The standard adds explicitly that objects with automatic storage duration are **not** destroyed as a result of calling `std::exit`. ## What that means for objects in the call stack | Object | `return` from `main` | `std::exit` called in a nested function | |---|---|---| | locals of the function calling `std::exit` | not applicable | **not destroyed** | | locals of `main` | destroyed | **not destroyed** | | `thread_local` objects of this thread | destroyed | destroyed | | static objects | destroyed | destroyed | | `atexit` handlers | called | called | | C streams (`stdout`, `FILE*`) | flushed and closed | flushed and closed | A run of the snippet below shows it. On `return` from `main` it prints `buffered line`, `~local`, `atexit handler`, `~static`; with `std::exit(3)` it prints `buffered line`, `atexit handler`, `~static`, and `~local` is missing. ## Why skipped destructors lose data RAII objects frequently hold buffered state: - A local `std::ofstream` writes through its own buffer; only its destructor (or an explicit `flush()`/`close()`) is guaranteed to push the last bytes to the file. `std::exit` does not run it. - A local lock guard, transaction or temporary-file remover never gets to release, commit or delete. - Output written with `std::cout` survives `std::exit`: the standard stream objects are never destroyed, but `<iostream>` behaves as if it defined a static `std::ios_base::Init` object, and that object's destructor calls `cout.flush()` when static objects are destroyed. A local `ofstream` gets no such help. ## A build tool that exits from deep inside Consider a build tool whose dependency scanner calls `std::exit(EXIT_FAILURE)` when it meets a malformed manifest, five calls below `main`: 1. `main` created a `TempDir` object that removes a scratch directory in its destructor. 2. A `std::ofstream` writing the build log is local to the build driver. 3. The scanner prints its message and calls `std::exit`. The status is correct, so CI marks the step failed, but neither destructor runs: the scratch directory stays behind, and the last lines of the build log, still in the stream's buffer, may never reach the file. The developer who opens the log finds it cut off right before the interesting part. Replacing the call with `throw ManifestError(...)` and catching in `main` fixes both, with the same status. ## When `std::exit` is still used - In a small tool with no meaningful locals when it decides to stop. - From an argument-parsing helper called before any resources exist. - Never from a destructor of a static or thread-local object: calling `std::exit` during that destruction is undefined behaviour. A cleaner pattern that keeps destructors running is to **throw an exception that `main` catches** and turn it into a return value. The standard itself notes that all automatic objects are destroyed when `main` has none of its own and calls `exit()` after control reaches it by an exception caught in `main`. ## `atexit` details worth knowing - `std::atexit(f)` registers a function with no parameters; registration returns zero on success, and at least 32 registrations are supported. - A function registered several times is called that many times. - If a registered function exits via an exception, `std::terminate` is called. - Registrations made after `std::exit` has started are not guaranteed to succeed. - `std::atexit` registrations are separate from `std::at_quick_exit` ones; register with both if a function must run on either path. ## Other threads `std::exit` destroys static objects while other threads may still be using them. The standard makes such uses undefined behaviour, and terminating every thread before calling `std::exit` or returning from `main` is the simple way to satisfy it.
- In what order do static destructors and atexit handlers run?Roughly as a stack. Static objects are destroyed in reverse order of the completion of their construction, `atexit` handlers run in reverse order of registration, and the two interleave: a handler registered after an object was constructed runs before that object is destroyed, and an object constructed after a registration is destroyed before that handler runs. Objects with constant destruction are destroyed after all the others.
- How can a deeply nested function end the program while still running every destructor?Throw an exception that `main` catches, and return an exit status from the handler. Unwinding destroys every automatic object between the `throw` and `main`'s handler, `main`'s locals are destroyed by the return, and `std::exit` then handles the statics. A dedicated exception type, such as one carrying the intended status, keeps it distinct from real errors.
- std::exit unwinds the stack and destroys local objects.
- std::exit skips static destructors and atexit handlers.
- Calling std::exit from a static object's destructor is a clean way to stop.
- atexit handlers run in registration order.
- A local std::ofstream is always flushed when the program exits.