R@M3$H.NBlog

Stack Unwinding

26 September, 2013 - 2 min read

Definition: As you create objects statically (on the stack as opposed to allocating them in the heap memory) and perform function calls, they are "stacked up".

When a scope (anything delimited by { and }) is exited (by using return XXX;, reaching the end of the scope or throwing an exception) everything within that scope is destroyed (destructors are called for everything). This process of destroying local objects and calling destructors is called stack unwinding. (Exiting a code block using goto will not unwind the stack which is one of the reasons you should never use goto in C++).

You have the following issues related to stack unwinding:

  1. avoiding memory leaks (anything dynamically allocated that is not managed by a local object and cleaned up in the destructor will be leaked) - see RAII referred to by Nikolai, and the documentation for boost::scoped_ptr or this example of using boost::mutex::scoped_lock.
  2. program consistency: the C++ specifications state that you should never throw an exception before any existing exception has been handled. This means that the stack unwinding process should never throw an exception (either use only code guaranteed not to throw in destructors, or surround everything in destructors with try { and } catch(...) {}).

If any destructor throws an exception during stack unwinding you end up in the land of undefined behavior which could cause your program to treminate unexpectedly (most common behavior) or the universe to end (theoretically possible but has not been observed in practice yet).

END