tags:

views:

79

answers:

3

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?

+4  A: 

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.

Tyler McHenry
+5  A: 

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.

GMan
+2  A: 

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.

Thanks for the information about copying
Net Citizen