C ++删除对象不会释放内存 [英] c++ deleting object do not free memory

查看:115
本文介绍了C ++删除对象不会释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下代码,以检查如何使用qt和c ++分配和释放内存

I have following code which I created to check how memory can allocate and free using using qt and c++

平台:Linux,Ubunut 16.04

testmemeory.h

#include <QObject>

class testMemeory : public QObject
{
    Q_OBJECT
public:
    explicit testMemeory(QObject *parent = nullptr);
    void freeMEm();
    char* str;

};

testmemeory.cpp

testMemeory::testMemeory(QObject *parent) : QObject(parent)
{
        str = new char [30000];
}

void testMemeory::freeMEm(){
    delete [] str;
}

这是我用来存储对象的数组.

This is the array I used to store the object.

std::vector<testMemeory*> testList;

我正在使用

void MainWindow::allocateMemory()
{
    for(int i=0;i<50000;i++){
        testMemeory *t = new testMemeory();
        testList.push_back(t);
    }

    qDebug()<<"Memory allocated..";
}

然后使用

void MainWindow::relaseMemory()
{
    for(int i=0;i<testList.size();i++)
        testList.at(i)->freeMEm();

    qDeleteAll(testList);
    testList.clear();

    qDebug()<<"Memory freed..";

}

当我分配内存时,用于该应用程序的RAM从150MB增加到了约350MB,好像调用relaseMemory()函数时,RAM仍然是350 MB,并且没有减少到150 MB

When I excute allocate memory the RAM used for the application increased from 150MB to about 350MB where as if call relaseMemory() function the RAM is still 350 MB and it not reducing to 150 MB

可能是什么原因.

推荐答案

通常,当应用程序需要内存时,它会从进程内内存舞台请求内存,如果内存不足,则舞台将从主机获取更多内存环境.然后根据需要将其从竞技场分发出去.

Typically, when an application needs memory, it requests it from an in-process memory arena and, if there's not enough, the arena will get more from the host environment. Then it's handed out from the arena as needed by individual allocations.

应用程序完成一点内存后,会将其交还给竞技场以供以后分配.通常不会从竞技场移交给主持人.

When the application is finished with a bit of memory, it hands it back to the arena for later allocations. It typically doesn't get handed back from the arena to the host.

因此,如果您要从 host的角度来衡量为应用程序分配了多少内存,它会上升但不会下降,至少直到应用程序退出为止,这时将返回所有 进程内存.

So, if you're measuring how much memory is allocated to the application from the point of view of the host, it will tend to go up but not down, at least until the application exits, at which point all process memory will be given back.

换句话说,是这样的:

+-------------+               +-------+
|             | <- allocate - |       |             +------+
| application |               | arena | <- obtain - | host |
|             | --- free ---> |       |             +------+
+-------------+               +-------+                 ^
\_____________________________________/                 |
                   |                                    |
                   +------ all handed back on exit -----+

这篇关于C ++删除对象不会释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆