将被抛出异常是否抛出。(如果抛出异常而未捕获,则可能无法解除该程序,但程序无论如何都会崩溃)。 < P> C++,使用这个概念。,c++,exception-handling,C++,Exception Handling" /> 将被抛出异常是否抛出。(如果抛出异常而未捕获,则可能无法解除该程序,但程序无论如何都会崩溃)。 < P> C++,使用这个概念。,c++,exception-handling,C++,Exception Handling" />

抛出异常时如何清除动态内存? void a(){ int*ptr=新的int(10); 抛出1;//内存分配后抛出 删除ptr; } int main(){ 试一试{ a(); }捕获(…){ 不能使用智能指针 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(){ 自动ptr=std::使_唯一(10); 投掷1枚; } PTR < /C>将被抛出异常是否抛出。(如果抛出异常而未捕获,则可能无法解除该程序,但程序无论如何都会崩溃)。 < P> C++,使用这个概念。

抛出异常时如何清除动态内存? void a(){ int*ptr=新的int(10); 抛出1;//内存分配后抛出 删除ptr; } int main(){ 试一试{ a(); }捕获(…){ 不能使用智能指针 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(){ 自动ptr=std::使_唯一(10); 投掷1枚; } PTR < /C>将被抛出异常是否抛出。(如果抛出异常而未捕获,则可能无法解除该程序,但程序无论如何都会崩溃)。 < P> C++,使用这个概念。,c++,exception-handling,C++,Exception Handling,简而言之:不要不必要地使用动态分配的内存,因此在您的情况下 void a(){ auto ptr = std::make_unique<int>(10); throw 1; } 没有新的,如果您不能做到这一点,请让一些基于范围的所有者处理生命周期: void a(){ int i; throw 1; // No dynamic allocation, no problem } void a(){ 自动ptr=std::使_唯一(10)

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

void a(){
    auto ptr = std::make_unique<int>(10);
    throw 1;
}
没有新的,如果您不能做到这一点,请让一些基于范围的所有者处理生命周期:

void a(){
    int i;
    throw 1;        // No dynamic allocation, no problem
}
void a(){
自动ptr=std::使_唯一(10);
抛出1;//分配处理正确,没有问题
}
这将在
int
超出范围时自动删除它


经验法则:如果您的代码有
delete
delete[]
或裸
new
new[]
,您可能有一个bug。

这就是为什么RAII是好的!为什么您会否决这个完全合理、清晰和简洁的问题?谢谢melak47,我知道可以使用类。如果您使用的是遗留代码“如果您的代码具有删除[]或全新[]或全新[],我正在尝试理解如何处理此内存线索。”这应该写在任何介绍动态内存分配的书籍章节的开头。
void a(){
    auto ptr = std::make_unique<int>(10);
    throw 1;        // Allocation handled properly, no problem
}