引发异常时如何清除动态内存


void a(){
    int *ptr = new int(10);
    throw 1;        // throwing after memory allocation
    delete ptr;
}
int main(){
    try{
        a();
    } catch(...){
        cout << "Exception"<<endl;
    }
 }

该程序会导致内存泄漏,有没有办法清除分配的动态内存..?

使用智能指针。

void a(){
    auto ptr = std::make_unique<int>(10);
    throw 1;
}

无论是否引发异常,都将解除分配ptr。(如果抛出异常且未捕获,则可能不会解除分配,但程序无论如何都会崩溃。

在C++中,您使用称为RAII的概念。

简而言之:不要不必要地使用动态分配的内存,所以在您的情况下

void a(){
    int i;
    throw 1;        // No dynamic allocation, no problem
}

没有new,如果您不能做到这一点,请让一些基于范围的所有者处理生命周期:

void a(){
    auto ptr = std::make_unique<int>(10);
    throw 1;        // Allocation handled properly, no problem
}

这将在int超出范围时自动删除它。

经验法则:如果你的代码有deletedelete[]或裸newnew[],你可能有一个错误。

最新更新