Re: exception handling, function call and memory
Ben Voigt [C++ MVP] wrote:
I heard somewhere that there's a table used during unwinding which
matches program counter to the list of handlers, as well as type and
relative stack locations for each auto variable requiring
destruction.
IIUC, that's how it works for x64 and IA64. For x86 it uses the linked list
of frames as Igor described. Those frames are by convention allocated on
the stack, but I don't think they're technically required to be there (not
that there's any other obvious place to put them, given their
lifetime/scope, etc).
I think by walking the stack during the search for the
exception handler, and accessing data structures built at
compile-time, the C++ exception handling mechanism actually entirely
avoids the runtime costs associated with managing an exception
handler stack, which is to say, with /EHa there's one SEH exception
handler added to the OS handler stack by the CRT at thread
initialization and no additional stack entries are needed.
That's true for the fully table-based implementation: virtual zero cost for
the non-exceptional case. VC++/x86 incurs cost for every exception frame
that's entered or left, regardless of whether an exception is thrown
in/through that frame.
Another interesting tidbit: C++ "stack unwinding" only talks about
destructors of local objects and the order in which they must run while
saying nothing about the actual recovery of memory allocated to the stack.
In the VC++ x86 implememtation, the stack space is not actually reclaimed
until the catch clause that handles the exception is exited normally (i.e.
not via another throw). If you look at the stack from within a catch block,
you'll see that it's consistent with the CRT "calling" the catch block as a
function. Only when that function returns is the (arbitrarily deep) stack
space actually reclaimed (via simple pointer adjustment). Destructors for
stack-based variables have, of course, already been run on all the objects
in that space before entering the catch block.
-cd