How are exceptions allocated on the stack caught beyond their scope?

前端 未结 6 1536
小蘑菇
小蘑菇 2020-12-09 08:44

In the following code, the stack-based variable \'ex\' is thrown and caught in a function beyond the scope in which ex was declared. This seems a bit strange to me, since (A

6条回答
  •  余生分开走
    2020-12-09 09:16

    C++ Standard 15.1/4:

    The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.3.1. The temporary persists as long as there is a handler being executed for that exception. In particular, if a handler exits by executing a throw; statement, that passes control to another handler for the same exception, so the temporary remains. When the last handler being executed for the exception exits by any means other than throw; the temporary object is destroyed and the implementation may deallocate the memory for the temporary object; any such deallocation is done in an unspecified way. The destruction occurs immediately after the destruction of the object declared in the exception-declaration in the handler.

    There is nothing more to say.

提交回复
热议问题