0

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?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • You know, you can easily check all those cases by simply implementing those and then debugging the application... – rbaleksandar Sep 15 '15 at 08:40
  • @rbaleksandar Not really. You might end up with something that seems to work for your particular compiler and runtime but is actually undefined behavior. – dhke Sep 15 '15 at 08:43

2 Answers2

4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

when is a temporary object destructed

After the full expression completes.

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?

Yes

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;.

Yes, it will

But I can always cout the right string. I'm just lucky or p is NOT illegal?

Because in the case of std::cout the full expression only completes after the semicolon.

Can we throw a temporary object in a function and catch it at its higher-level function with a const reference?

Yes, you can: This link has a good explanation of the exception object lifetime. I think of it that the exception expression ends when the exception is caught (but that's just a way of thinking about it).

Werner Erasmus
  • 3,988
  • 17
  • 31