catching exception objects by reference, temporaries, lifetime issues

前端 未结 4 830
独厮守ぢ
独厮守ぢ 2021-01-13 03:55

Consider the following code:

#include 
#include 

void foo()
{
    throw std::runtime_error(\"How long do I live?\");
}

int         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-13 03:56

    In the C++ standard, paragraph 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.

    Note that, in C++-standard talk, a handler denote a catch block with the correct argument type.

提交回复
热议问题