Throwing object exceptions on stack, mem leak with new?

This is mistake:

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'd:

 catch(const Cat &c) { } 

If this is not valid, I use the new Cat ("Minoo");

Could this cause a memory leak?

+2
c ++ exception
source share
3 answers

1) Wrong? No, this is what you have to do: drop the object. An object in a throw-statement may be on the stack, but it is copied when it is thrown. Compare, for example, the effect of performing a Cat return ("Minoo");

2) Will a pointer be thrown so that the object pointing to the object is leaked? Yes, if the object has been allocated to the heap and if you do not delete it. But you should avoid specifying pointers as a general rule.

+6
source share

Now you have what everyone should do, and most of them. Throw away the object itself and catch the const-reference.

Cast pointers have hairy problems, such as "who removes it?".

More info here .

+6
source share

What you wrote is absolutely correct and it is usually preferable to allocate exception objects on the heap.

If you used a new one, you will certainly get a memory leak unless you delete the object in the exception handler that caught the exception.

This question in C ++ faq (and two afterword questions) addresses this.

+5
source share

All Articles