Reputation: 35
It's illegal to throw an exception from a function like this?
In Eclipse it work...
So it's true? and we can throw internal object in throwing exceptions?
class Bad {
int i;
public:
void what() { cout << "exp" << i; }
};
class A {
public:
void f() {
Bad e;
throw e;
} // e are deleted by d'tor?
};
int main() {
A a;
try {
a.f();
} catch (Bad& e) // What happen here? we catch reference to some object that
// was deleted by Bad dt'or
{
cout << "in catch";
e.what(); // what happen here?
}
return 0;
}
Upvotes: 1
Views: 126
Reputation: 254631
Your code is fine. throw e;
makes a copy of e
, which is destroyed after the exception has been handled. The handler is given a reference to that copy.
You could get in trouble if you threw a pointer to the local variable; the variable would be destroyed before handling the exception, leaving the pointer invalid. But throwing a pointer would be rather an odd thing to do in any case.
Upvotes: 3