0

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"};
}
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331

3 Answers3

4

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.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
2

Yes, they will be deallocated:

  • First, their destructors, if any, are going to be invoked,
  • Then their memory will be deallocated from the automatic storage area.

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

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

aliasm2k
  • 883
  • 6
  • 12