QList erase 函数的问题 !

kusey 2011-09-22 02:53:26
我的 QList 里面放的是指针,所以 erase 的时候需要把该指针从 list 中拿出来,同时需要释放该指针指向的内存,所以我的代码如下:


if( *(iter) == xxxxx ) {
mylist.erase( iter );
delete (*iter);
}

// ......

qDeleteAll( mylist );
mylist.clear();


执行到 qDeleteAll 的时候程序崩溃,请问我该怎么写?
...全文
1146 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
-k3- 2011-09-25
  • 打赏
  • 举报
回复
erase 的时候会改变 iterator 的值,会指向下一个值。所以delete 的时候其实是delete 了一下个。
deleteAll的时候就会出错了。

当iterator= 最后一个时,delete 这局也会出错。。


Lutx 2011-09-23
  • 打赏
  • 举报
回复
qDeleteAll已经可以帮你做这个事情了, 所以只要调用这句就可以了.
如果只想清除列表内容, 而不像释放列表中指针所指的对象, 那应该用mylist.clear();

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 *).

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.
情歌而已 2011-09-22
  • 打赏
  • 举报
回复
我觉得原因在于你外层包的for循环,千万不要在for循环遍历的时候插入或删除元素,这样会导致下标(元素在容器中的位置)发生改变,造成越界或者其他后果
donwmufromdying 2011-09-22
  • 打赏
  • 举报
回复
if( *(iter) == xxxxx ) {
mylist.erase( iter );
delete (*iter);
}
写反了!
改成:
if( *(iter) == xxxxx ) {
delete (*iter);
mylist.erase( iter );
}

我很少用erase.我一般用remove的多。据说这两个应该是一样的。
如果要删除整个list里边的这种对象指针。用qDeleteAll(myList)
kusey 2011-09-22
  • 打赏
  • 举报
回复
好像 erase 的时候它会自动把内存释放掉,所以不必再 delete 了,是这样么?

16,216

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧