1. 程式人生 > >QList指標中的clear後不會自動釋放記憶體,需要之前呼叫qDeleteAll()

QList指標中的clear後不會自動釋放記憶體,需要之前呼叫qDeleteAll()

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); } slist.clear(); return a.exec();}

將上面程式碼中的slist.clear(); 註釋掉,記憶體顯示為如下(工作管理員裡的截圖)

111

如不去掉的話,記憶體顯示如下圖

22222

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();    return a.exec();}

上面程式碼執行後的記憶體情況如下圖

3333

說明當T的型別為指標時,呼叫clear()方法並不能釋放其記憶體

此時void qDeleteAll ( const Container & c )方法將派上用場了,將上面程式碼中的註釋去掉以後,

再次執行程式,此時的記憶體情況如下圖

4444

通過對比靚圖,可以看出,記憶體已經釋放,我們再來看下qt助手中qDeleteAll 方法的說明

void qDeleteAll ( ForwardIterator begin, ForwardIterator end )

Deletes all the items in the range [beginend) 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.

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 方法。