[转]QList内存释放
QList<T> 的释放分两种情况:
1.T的类型为⾮指针,这时候直接调⽤clear()⽅法就可以释放了,看如下测试代码
#include <QtCore/QCoreApplication>
#include <QList>
#include <QString>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
typedef struct _test
{
int id;
QString name;
QString sex;
}Por_test;
QList<Por_test>  slist;
for (int i=0;i<100000;i++)
{
Por_test s;
s.id = 1;
s.name = QString("hello World!");
s.sex = QString("男");
slist.append(s);
}delete in
slist.clear();
();
}
将上⾯代码中的slist.clear(); 注释掉,内存显⽰为如下(任务管理器⾥的截图)
如不去掉的话,内存显⽰如下图
2.T的类型为指针的情况,这时候直接调⽤clear()⽅法将不能释放,先看代码
#include <QtCore/QCoreApplication>
#include <QList>
#include <QString>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
typedef struct _test
{
int id;
QString name;
QString sex;
}Por_test;
QList<Por_test *>  slist;
for (int i=0;i<100000;i++)
{
Por_test *s = new Por_test();
s->id = 1;
s->name = QString("hello World!");
s->sex = QString("男?");
slist.append(s);
}
//    qDeleteAll(slist);
slist.clear();
();
}
上⾯代码运⾏后的内存情况如下图
说明当T的类型为指针时,调⽤clear()⽅法并不能释放其内存
此时void qDeleteAll ( const Container & c )⽅法将派上⽤场了,将上⾯代码中的注释去掉以后,
再次运⾏程序,此时的内存情况如下图
通过对⽐靓图,可以看出,内存已经释放,我们再来看下qt助⼿中qDeleteAll ⽅法的说明
void qDeleteAll ( ForwardIterator begin, ForwardIterator end )
Deletes all the items in the range [begin, end) using the C++ delete operator. The item type must be a pointer type (for example, QWidget *).
Example:
QList<Employee *> list;
list.append(new Employee("Blackpool", "Stephen"));
list.append(new Employee("Twist", "Oliver"));
qDeleteAll(list.begin(), d());
list.clear();
Notice that qDeleteAll() doesn't remove the items from the container; it merely calls delete on them. In the example above, we call clear() on the container to remove the items.
This function can also be used to delete items stored in associative containers, such as and . Only the objects stored in each container will be deleted by this function; objects used as keys will not be deleted.
See also .
void qDeleteAll ( const Container & c )
This is an overloaded member function, provided for convenience.
This is the same as qDeleteAll(c.begin(), c.end()).
上⾯qDeleteAll ⽅法的说明,已经很清楚了,如果T为指针类型时,释放内存须在clear⽅法前加上qDeleteAll ⽅法。