TITLE: destruction and program exit (Newsgroups: comp.lang.c++.moderated, 28 May 98) UNKNOWN: >>>>...and call exit with the argument given in the constructor. PHLIP: >>> I have been telling students that this does not call the >>> destructor of every stack object between here and 'main'. >>> As such it is undefined behavior, although most modern OSs >>> are built to survive it. CLAMAGE: clamage@Eng.Sun.COM (Steve Clamage) It's more of a program correctness issue. If a constructor locked a database (for example) that the destructor was supposed to unlock, whether the whole system ground to a halt would depend on whether the lock got released automatically when this program terminated. MARTIN: Robert Martin >>Section 12.2.3 of the draft says: >> >>3 When an implementation introduces a temporary object of a class that >> has a non-trivial constructor (_class.ctor_), it shall ensure that a >> constructor is called for the temporary object. Similarly, the >> destructor shall be called for a temporary with a non-trivial destruc- >> tor (_class.dtor_). PHLIP: >Interpretation: The implementation ensures a destructor exists and is >called. MARTIN: >> Temporary objects are... PHLIP: >....destroyed. MARTIN: >> This is true even if that >> evaluation ends in throwing an exception. PHLIP: >'exit' is not an exception - it is a black hole out of which no control flow >can escape. (But of course the static destructors call here!) CLAMAGE: The behavior of exit is specified in draft standard section 18.3 "Start and termination". It says that automatic objects are not destroyed as a result of calling exit. Objects with static storage duration are destroyed. We could compare exit with other forms of program termination. If the program terminates normally by returning from main, all static and automatic objects get destroyed. If the program terminates by calling abort or terminate, no objects get destroyed. If the program terminates via an uncaught exception, terminate gets called, meaning no static objects get destroyed. Whether auto objects get destroyed is up to the implementation. (If you are running under a debugger, you wouldn't want the stack to be unwound, so that you could trap the uncaught exception and examine the program state at the point where it was thrown.)