Consider the following code:
#include <iostream>
#include <stdexcept>
void foo()
{
throw std::runtime_error("How long do I live?");
}
int main()
{
try
{
foo();
}
catch (std::runtime_error& e)
{
std::cout << e.what() << std::endl;
}
}
Why can I catch the exception by reference, isn't std::runtime_error("How long do I live?")
an rvalue?
How come the exception object is still alive in the catc开发者_JAVA技巧h block?
Where exactly are thrown exception objects stored? What is their lifetime?
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.
A thrown exception is not a temporary - the compiler-generated exception code keeps a permanent copy of it. So you can bind it to a non-const reference.
[edit] I just check the standard and it actually refers to a temporary copy. However, the lifetime of the temporary is guaranteed to be at least as long as that of the exception handler.
As Neil said, there is internal compiler magic going on. Also, be aware that the compiler is allowed to create any number of copies of the exception object.
Kudos for trying to understand the details of the language. At the same time, IMHO, it is far more important to understand why you should catch an exception by reference (and throw it by value), than why you can.
People typically use a hierarchy of exception classes, and catching by reference allows you to leverage polymorphism, and catch an exception of the base class, when there is no need to handle individual exception types separately. If you couldn't catch by reference, you would have had to write a catch
clause for every possible type of exception that can be thrown in the try
clause.
精彩评论