throwing exceptions of objects on the stack, mem l

2020-03-29 05:16发布

问题:

Is it a bug to do this:

if(some_error)
  throw Cat("Minoo");

Where Cat is a class.

Then in some other function that called the method that threw the exception...

I would have:

catch(const Cat &c)
{ 
}

If it is invalid, do I use new Cat("Minoo");

Would that cause a memory leak?

回答1:

1) Invalid? No, that's precisely what you're supposed to do: throw an object. The object in the throw-statement may be on the stack, but it is copied when it is thrown. Compare, for example, the effect of executing return Cat("Minoo");

2) Will throwing a pointer cause the pointed-to object to be leaked? Yes, if the object was allocated on the heap and unless you arrange to delete it. But you should avoid throwing pointers as a general rule.



回答2:

What you have now is what everyone should be doing, and most do. Throw the object itself and catch by const-reference.

Throwing pointers has hairy issues such as "who deletes it?".

More information here.



回答3:

What you wrote is perfectly valid, and is generally preferable to allocating exceptions objects on the heap.

If you were to use new, you would of course get a memory leak unless you deleted the object in an exception handler that caught the exception.

This question in the C++ faq (and the two questions afterwords) address this.



标签: c++ exception