QList中的动态内存 [英] dynamic memory in QList

查看:553
本文介绍了QList中的动态内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在QT方面经验不足,今天就出现了这个问题.

I don't have much experience with QT and this problem came out today.

QList<int> memList;
const int large = 100000;

getchar();
for (int i=0; i<large; i++)
{
    memList.append(i);
}

cout << memList.size() << endl;
getchar();

for (int i=0; i<large; i++)
{
    memList.removeLast();
}

cout << memList.size() << endl;
getchar();

在第一次循环后,当我检查内存使用率时,它会随着新元素添加到memList而上升,但是在第二次循环中删除它们之后,内存使用率将保持在同一水平.我认为QList是动态的,当元素被删除时它将释放内存.因此,我错过了某些东西(很有可能)或它不是动态结构.您有任何想法如何使其工作吗?

After first loop when I check memory usage it goes up as new elements are appended to the memList but after removing them within second loop the memory usage stays at the same level. I thought that QList was dynamic and it would free memory when element is removed. So either I'm missing something (very probable) or it is not dynamic structure. Do you have any ideas how to make it work?

致谢

推荐答案

来自文档看来这是预期的行为:

From the docs it appears that this is the expected behaviour :

请注意,内部数组只会在列表的整个生命周期内变大.它永远不会收缩.当一个列表分配给另一个列表时,内部数组由析构函数和赋值运算符释放.

Note that the internal array only ever gets bigger over the life of the list. It never shrinks. The internal array is deallocated by the destructor and by the assignment operator, when one list is assigned to another.

如果您要取消分配内存,则有两种选择

If you want to de-allocate the memory you've got a couple of options

  1. 确保调用了析构函数(使用delete {首先假设您要新建列表),或允许QList对象超出范围)
  2. 将一个空列表分配到您的大列表中(认为这会起作用)

这篇关于QList中的动态内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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