What is Stack Unwinding ?
local objects are invoked.
--------------------------------------------------------------------------------------------------------------------------
When an exception is thrown and control passes from a try block to a handler, the C++ run time calls destructors for all automatic objects constructed since the beginning of the try block. This process is called stack unwinding. The automatic objects are destroyed in reverse order of their construction
Consider the following code
The flow of the program:
The process of searching ‘‘up through the stack’’ to find a handler for an exception is commonly
called ‘‘stack unwinding.’’ As the call stack is unwound, the destructors for constructed
local objects are invoked.
--------------------------------------------------------------------------------------------------------------------------
When an exception is thrown and control passes from a try block to a handler, the C++ run time calls destructors for all automatic objects constructed since the beginning of the try block. This process is called stack unwinding. The automatic objects are destroyed in reverse order of their construction
Consider the following code
void g() { throw std::exception(); } void f() { std::string str = "Hello"; // This string is newly allocated g(); } int main() { try { f(); } catch(...) { } }
main()
callsf()
f()
creates a local variable namedstr
str
constructor allocates a memory chunk to hold the string"Hello"
f()
callsg()
g()
throws an exceptionf()
does not catch the exception.
- Because the exception was not caught, we now need to exit
f()
in a clean fashion. - At this point, all the destructors of local variables previous to the throw
- are called—This is called 'stack unwinding'.
- The destructor of
str
is called, which releases the memory occupied by it.
- As you can see, the mechanism of 'stack unwinding' is essential to prevent resource leaks—without it,
str
would never be destroyed, and the memory it used would be lost until the end of the program (even until the next loss of power, or cold boot depending on the Operative System memory management).
main()
catches the exception- The program continues.