Memory deallocation and exceptions

2020-03-19 02:13发布

问题:

I have a question regarding memory deallocation and exceptions. when I use delete to delete an object created on the heap . If an exception occurs before this delete is the memory going to leak or this delete is going to execute ?

回答1:

This depends on where that delete is. If it's inside the catch that catches the exception, it might invoke.

try {
    f();  // throws
} catch( ... ) {
    delete p;  // will delete
}

If it's after the catch that catches the exception and that catch doesn't return from the function (i.e. allows execution flow to proceed after the catch block) then the delete might be called.

try {
    f();  // throws
} catch( ... ) {
    // execution proceeds beyond catch
}
delete p;  // will delete

If the delete is not in a catch block or after a catch block that allows execution to proceed then the delete will not call.

try {
    f();  // throws
    delete p;  // will not delete
}  // ...

As you may imagine, in the two first cases above the delete will not be invoked if there is a throw before the delete:

try {
    f();  // throws
} catch( ... ) {
    g();  // throws
    delete p;  // will not delete
}


回答2:

In the case you describe, memory is going to leak.

Two tricks to avoid this problem :

  • use smart pointers, which don't suffer from the same problem (preferred solution)
    --> the smart pointer in constructed on the stack, its destructor is therefore called, no matter what, and deletion of the pointed content is provided in the destructor

  • use try/catch statements, and delete the item in catch statement as well



回答3:

It won't be called. Which is why you are encouraged to look at RAII. See Stroustrup



回答4:

We also have to make sure that "exception" really means C++ exception which can be caught by try/catch. There are other exceptions as well in the system which C++ try/catch cannot catch (e.g. division by 0).

In such cases(beyond the scope of C++ Standards), also, "delete" will not be executed unless these exceptions are caught and the handler explicitly invokes "delete" appropriately.



标签: c++ exception