The C++ standard specifies (in so many words) that returning from main
is equivalent to calling std::exit
.
main function [basic.start.main]
A return statement in main has the effect of leaving the main function
(destroying any objects with automatic storage duration) and calling
std::exit with the return value as the argument. If control flows off
the end of the compound-statement of main, the effect is equivalent to
a return with operand 0.
exit
is defined as follows (irrelevant details omitted):
Startup and termination [support.start.term]
[[noreturn]] void exit(int status);
Effects:
— First, objects with thread storage duration and associated
with the current thread are destroyed. Next, objects with static
storage duration are destroyed and functions registered by calling
atexit are called.
— Next, all open C streams ... are removed.
— Finally, control is returned to the host environment. If status is
zero or EXIT_SUCCESS, an implementation-defined form of the status
successful termination is returned. If status is EXIT_- FAILURE, an
implementation-defined form of the status unsuccessful termination is
returned.
It is not defined what happens if non-main execution threads are running when the main execution thread returns. The shown code does not guarantee that the non-main execution thread terminates/sequenced before main
returns.
As such, the only thing the standard specifies is that:
Global objects get destroyed
"Control is returned to the host environment", a.k.a.: "It's dead, Jim".
The standard does not define what happens if non-main execution threads are running when the main execution thread returns. A.k.a.: undefined behavior.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…