抛出异常时如何清除动态内存?

Dha*_*raj 0 c++ exception-handling

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

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

Bri*_*ian 5

使用智能指针.

void a(){
    auto ptr = std::make_unique<int>(10);
    throw 1;
}
Run Code Online (Sandbox Code Playgroud)

ptr无论是否抛出异常,都将被解除分配.(如果抛出异常但未被捕获,则可能不会被释放,但程序无论如何都会崩溃.)