当T为指针类型时,List.clear()不能释放其内存,需加上qDeleteAll()函数,

    //class Person ---> Person(int id_,QString name_)
    //当T的类型为指针时,调用clear()方法并不能释放其内存!
    //qDeleteAll(list.begin(),list.end());//<-要加这句话
    list.clear();
    for(int i=0;i<500000;i++){
        list.append(new Person(i,"eat memory ~~"));
        std::cout<<i<<"eat memory ~~"<<std::endl;
    }
  • 不加qDeleteAll()

  • 加了qDeleteAll()

  • 附: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(), 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()).

posted on 2017-08-21 22:22  tyw66  阅读(436)  评论(0编辑  收藏  举报