内存释放和异常 [英] Memory deallocation and exceptions

查看:106
本文介绍了内存释放和异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于内存释放和异常的问题。当我使用delete删除在堆上创建的对象时。

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 ?

推荐答案

这取决于在哪里执行 delete 是。如果它在捕获异常的 catch 中,它可能会调用。

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
}

如果它在 catch 捕获异常,并且 catch 不从函数返回(即允许执行流程在 catch block),则可能会调用 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

如果 delete 不在 catch 块中或在 catch 块后允许执行,然后 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
}  // ...

如果 delete

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

这篇关于内存释放和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆