Exceptions

Started by
2 comments, last by MutteringGoblin 20 years, 11 months ago
Hello, Something that''s been bothering me... and I can''t find the answer ''cos I took all my C++ books back to the library. If you throw an exception from a member function of a dynamically allocated object, is the object deleted? If not, how can you delete it? I''ll give an example: say I create an object dynamically inside a try block, using a local pointer. Then I call a member function of the object which throws an exception. The pointer is lost (I assume) when control passes to the next catch block. What happens to the object after that? PS I know I could use "delete this;" before throwing the exception but what effect would that have on local objects?
Advertisement
I don''t think the object is deleted, but there are loads of ways around this.

You could put the a pointer to the object in your exception class and call delete in your catch.

Declare the local pointer outside the scope of the try.

or as you said call delete this (but that can be dodgy unless you''re sure the object will only ever be dynamically allocated)

by the way I''m not sure what you mean by "what effect would that have on local objects?". Which local objects?
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
Hi Chaos,

Thanks for answering. By "local objects" I just meant non-dynamically allocated objects of the class throwing the exception.

Your first idea sounds good but if I copy the object''s address into an exception object, I still won''t know in the catch block whether it was a local object or a dynamic one. Unless I only create one sort of object in the try block, and any functions it calls.

I''m not trying to be difficult here, I just tend to think if something can go wrong it probably will! I don''t want to be on my guard all the time for obscure bugs. I''m still fairly new to C++ so maybe I''m worrying about nothing... it just seems like an accident waiting to happen.


ok the local variables of the method throwing the exception will go out of scope exactly as they would if you just "return"ed from the function. The class members (whether allocated on the stack or the heap) will remain in existence until you delete the object. Then you would clean up any heap objects in the destructor.

the best way to avoid this is to put the pointer declaration outside the try block as in:

  CObject* pObj = NULL;try {    pObj = new CObject();    pObj->SomeFuncThatThrowsAnException();}catch(CObjectException& obj) {    //handle exception and decide if you want to delete the object    delete pObj;}  
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

This topic is closed to new replies.

Advertisement