There are some cases:
case 1:
string("test");
int i = 1;
This is a temporary object. It will be destructed as soon as we arrive int i = 1;
. Am I right?
case 2:
const char * p = string("test").c_str();
int i = 1;
cout<< p;
I think p will point an illegal memory when we arrive int i = 1;
. But I can always cout
the right string. I'm just lucky or p is NOT illegal?
case 3:
void fun()
{
throw Exception("error");
}
int main()
{
try
{
fun();
}catch(const Exception & e)
{
cout << e.description();
}
}
Can we throw
a temporary object in a function and catch it at its higher-level function with a const reference?
In both case 1 and 2, the temporary object is destructed once the full expression it is in has been evaluated. In case 1 it's when the statement ends.
And in case 2, no you're not lucky, it's undefined behavior and that it seems to be working is just one of the possibilities of UB.
As for case 3, C++ will itself make sure that there is a valid instance all through the exception handling, and exception handlers can have references to that actual instance.