【问题标题】:What will happens if before freeing memory allocated by new operator, exception occurred?如果在释放 new 运算符分配的内存之前发生异常会发生什么?
【发布时间】:2019-06-17 19:34:30
【问题描述】:

我只是想知道,如果在释放 new 运算符分配的内存之前发生异常会发生什么?是不是发生了内存泄漏问题?

#include <iostream>
#include<new>

using namespace std;

void func()
{
    try
    {
        int *p = new int[10];

        /*
            Number of lines code here
            .
            .
            .
            .
            .
            Suppose here I got exception then What heppens????
            .
            .
            .
            .
        */
        delete []p;
    }
    catch(const std::exception& e)
    {
        cout<<"Exception occured"<<endl;
    }
}

int main() {
    func();
    return 0;
}

【问题讨论】:

    标签: c++ new-operator free dynamic-memory-allocation


    【解决方案1】:

    是不是发生了内存泄漏问题?

    是的。这就是设计智能指针和整个 RAII 习语的全部原因。当找到处理程序时,仍会调用块范围变量的析构函数,因此它们可以释放分配的资源。原始指针只会泄漏。

    【讨论】:

      【解决方案2】:

      由于从未调用过运算符delete 而发生内存泄漏。使用 std::unique_ptr&lt;T&gt; 而不是原始 C++ 指针。 C++ 标准库提供了std::unique_ptr&lt;T&gt;,它会在超出范围时自动取消分配包装的指针。 C++ 标准库还提供了std::shared_ptr&lt;T&gt;,它使用引用计数并仅在释放对指针的最后一个引用时才释放内存。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-20
        • 2016-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多