catching exception objects by reference, temporaries, lifetime issues

前端 未结 4 872
独厮守ぢ
独厮守ぢ 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 04:13

    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.

提交回复
热议问题