Sunday, January 25, 2015

Stack Unwinding

What is Stack Unwinding ?


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(...) 
    { }
}
The flow of the program:
  • main() calls f()
  • f() creates a local variable named str
  • str constructor allocates a memory chunk to hold the string "Hello"
  • f() calls g()
  • g()throws an exception
  • f() 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.
The 'stack unwinding' guarantees destructors of local variables (stack variables) will be called when we leave its scope.

Type Casting in C++

static_cast