当前位置: 动力学知识库 > 问答 > 编程问答 >

C++ - Do local objects deallocate if an exception is thrown?

问题描述:

This question already has an answer here:

  • Are destructors called after a throw in C++?

    2 answers

网友答案:

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.

网友答案:

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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: