QList<T> 的釋放分兩種情況:
1.T的類型為非指針,這時(shí)候直接調(diào)用clear()方法就可以釋放了,看如下測(cè)試代碼
#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); } slist.clear(); return a.exec();}
將上面代碼中的slist.clear(); 注釋掉,內(nèi)存顯示為如下(任務(wù)管理器里的截圖)

如不去掉的話,內(nèi)存顯示如下圖

2.T的類型為指針的情況,這時(shí)候直接調(diào)用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(); return a.exec();}
上面代碼運(yùn)行后的內(nèi)存情況如下圖

說(shuō)明當(dāng)T的類型為指針時(shí),調(diào)用clear()方法并不能釋放其內(nèi)存
此時(shí)void qDeleteAll ( const Container & c )方法將派上用場(chǎng)了,將上面代碼中的注釋去掉以后,
再次運(yùn)行程序,此時(shí)的內(nèi)存情況如下圖

通過(guò)對(duì)比靚圖,可以看出,內(nèi)存已經(jīng)釋放,我們?cè)賮?lái)看下qt助手中qDeleteAll 方法的說(shuō)明
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(), list.end()); 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 QMap and QHash. Only the objects stored in each container will be deleted by this function; objects used as keys will not be deleted.
See also forward iterators.
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 方法的說(shuō)明,已經(jīng)很清楚了,如果T為指針類型時(shí),釋放內(nèi)存須在clear方法前加上qDeleteAll 方法。