Search code examples
c++exceptionraiistack-unwinding

RAII and Stack unwinding


TIL that my notions of the 'inter-twining' (for the lack of a better word) of RAII & stack-unwinding are/were quite(if not completely) wrong. My understanding was that using RAII, guarded against any/all resource leaks - even ones potentially caused by unhandled exceptions.

However writing this test program and subsequently stumbling upon this article/documentation, made me realize that stack unwinding would only cause the RAII-enabled resource deallocation to kick in for automatic's within the try block as opposed to automatic's in, say, outer/other scopes.

Am I correct in this (new) understanding? Or are there further nuances I am yet not grasping? Any gurus out there want to chime in? Pointers to any good write-ups/analyses/explanations (of stack-unwinding) would be helpful/appreciated…


Solution

  • From the C++03 standard, §15.3/9:

    If no matching handler is found in a program, the function terminate() is called; whether or not the stack is unwound before this call to terminate() is implementation-defined (15.5.1).

    §15.5.1/1:

    In the following situations exception handling must be abandoned for less subtle error handling techniques: ... when the exception handling mechanism cannot find a handler for a thrown exception (15.3) ...

    §15.5.1/2:

    In such cases,

        void terminate();

    is called (18.6.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before terminate() is called. In all other situations, the stack shall not be unwound before terminate() is called. An implementation is not permitted to finish stack unwinding prematurely based on a determination that the unwind process will eventually cause a call to terminate().