Memory deallocation and exceptions

微笑、不失礼 提交于 2020-01-11 05:15:09

问题


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.



来源:https://stackoverflow.com/questions/3486524/memory-deallocation-and-exceptions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!