The Standard defines three ways to end execution of a C++ program:
- Return from
main
. Objects with automatic storage (function-local) have already been destroyed. Objects with static storage (global, class-static, function-static) will be destroyed.
std::exit
from <cstdlib>
. Objects with automatic storage are NOT destroyed. Objects with static storage will be destroyed.
std::abort
from <cstdlib>
. Objects with automatic and static storage are NOT destroyed.
Also relevant is std::terminate
from <exception>
. The behavior of terminate
can be replaced using std::set_terminate
, but terminate
must always "terminate execution of the program" by calling abort
or some similar implementation-specific alternative. The default is just { std::abort(); }
.
C++ will call std::terminate
whenever an exception is thrown and C++ can't reasonably do stack unwinding. For example, an exception from a destructor called by stack unwinding or an exception from a static storage object constructor or destructor. In these cases, there is no (more) stack unwinding done.
C++ will also call std::terminate
when a matching catch
handler is not found. In this single case, C++ may optionally unwind to main
before calling terminate
. So your example might have different results with a different compiler.
So if you use RAII correctly, the remaining steps to "leak-proof" your program are:
- Avoid
std::abort
.
- Either avoid
std::exit
or avoid all objects with static storage duration.
- Put a
catch (...)
handler in main
, and make sure no allocations or exceptions happen in or after it.
- Avoid the other programming errors that can cause
std::terminate
.
- (On some implementations, functions compiled with a C compiler act like they have C++'s empty
throw()
specification, meaning that exceptions cannot be thrown "past" them even though they have no destructors to be called.)