关于QList<T>的内存释放

当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()).

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值