I wanted to know if objects allocated in a stack get deallocated when an exception is thrown.
For example, in a function:
void some_function()
{
int i;
std::string str;
throw std::runtime_error{"Some error"};
}
I wanted to know if objects allocated in a stack get deallocated when an exception is thrown.
For example, in a function:
void some_function()
{
int i;
std::string str;
throw std::runtime_error{"Some error"};
}
Destructors of local objects are guaranteed to be invoked as part of stack unwinding if there is a handler for the exception.
If there is no handler then it's up to the implementation:
C++11 §15.5.1/2:” […] In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before
std::terminate()
is called.
Yes, they will be deallocated:
The second part is commonly implemented by removing the stack frame in which the object is allocated.
This feature is fundamental for implementing RAII, a technique for exception-safe resource management in C++.
Note: In case that there is no exception handler defined in your code the program is allowed to terminate without calling destructors, letting the operating system deal with the task of releasing the resources held by your program.
Local variables should be deallocated when an exception is thrown as the throw
clause returns the function to calling function.
Consider that your function some_function()
is called by main()
. In this case the throw
clause returns the function back to main
there by deallocating the local variable declared in some_function