c++ - 数组的资源泄漏

标签 c++ visual-c++ memory-management memory-leaks

我有以下类(class):

class estimate
{
    public:
        estimate();
        ~estimate();
        double *tHanning;
}

estimate::estimate()
{
    tHanning = NULL;
    tHanning = new double [1000];

    for (int m=0; m<1000; m++)
    {
        tHanning[m]=(0.5-0.5*cos(2.0*PI*(m+1)/(1001))); 
    }
}

estimate::~estimate()
{
    delete [] tHanning;
    tHanning = NULL;
}

我不确定为什么当我将“new”分配给变量时,C++ Memory Validator 在构造函数中显示资源泄漏。

有人可以帮我吗?

编辑:我如何起诉上述类(class):

class HBMain
{
    public:
        HBMain();
        ~HBMain();
        bool Init();
        estimate *objEstimate;
}

HBMain :: HBMain()
{
    objEstimate = NULL;
}

HBMain :: ~HBMain()
{
    delete objEstimate;
    objEstimate = NULL;
}

bool HBMain :: Init()
{
    ....
    objEstimate = new estimate();
    ....
}

最佳答案

作为替代解决方案,为什么不简单地将指针更改为 double vector ?

您将避免因内存泄漏而头痛。

编辑:对于 HBMain 类,您还可以通过 C++11 或 Boost 库中的智能指针 (shared_ptr) 更改裸指针,并删除析构函数。因此您不必实现所有样板代码。

但是,您真的需要对 HBMain 属性进行动态分配吗?

关于c++ - 数组的资源泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17925713/

相关文章:

windows - 如何在 win32 进程中显示 'memory used' 的百分比?

c++ - 使用基于 bool 值的两种方法之一调用方法时如何确保避免分支预测错误

c++ - 错误 C2535 : member function already defined or declared

memory-management - Swift 5 - 模拟器启动时显示白屏 - 仪器

c++ - 错误 : ‘log2’ is not a member of ‘std’

c++ - 检查鼠标是否在三角形 C++ 内

c++ - 跟踪 C++ 中的内存使用情况并评估内存消耗

c++ - 如何向链表添加内容

c++ - 非循环访问者模式。将接受功能移动到一个地方

c++ - QTcpSocket readyRead() 信号发出两次