【发布时间】:2014-10-03 16:49:58
【问题描述】:
如果我有以下情况:
try{
int* i = new int(5);
//exception thrown here
}
catch(const exception& e){
//Do I need to delete the heap allocation here?
}
在抛出异常之前不久进行堆分配,作为堆栈展开的一部分,堆内存会被回收吗?还是会出现内存泄漏,我应该在catch() 语句中处理这个问题?
【问题讨论】:
-
你会有内存泄漏。你需要删除
catch子句中的内存。 -
然而,如果你把它设为
unique_ptr<int> i{new int(5)};,那么实际上内存将在堆栈展开期间被unique_ptr的析构函数释放。这就是智能指针的要点。 -
只有当你说应该的时候,比如正确使用 RAII 或添加手动步骤。 Igor 展示了一种使用 RAII 的方法。
标签: c++ exception memory-management memory-leaks exception-handling