[Kde-games-devel] Re: test QPtrList existence ?
Andreas Beckermann
b_mann at gmx.de
Sun Sep 21 00:32:57 CEST 2003
On Saturday 20 September 2003 18:47, cantabile wrote:
> Hi,
> I encounter a simple problem with QPtrList, but can't see why:
> when my game is ending, I call a clear() function, which erase the
> values in a QPtrList<QCanvasItems>.
>
> When the list has not been used (e.g I call a new game at the start,
> without erasing any value in the list), no problem, but when it's been
> used, I get a crash pointing to my clear() methtod.
>
> Here's the method :
>
> void KMatchesView::clear()
> {
> if (!matchesList.isEmpty())
> for (uint i=0; i< matchesList.count() ; i++) {
> QCanvasItem* match = matchesList.at(i);
> if (match->rtti() == matchRTTI) {
> delete match;
Are you sure you want to do this?
Imagine a list with 2 elements. You start at i==0, the item matchesList.at(0)
is deleted. Now your list has one entry only.
The next loop iteration (i==1) will stop the loop, as i==matchesList.count()
==1. The second item is never deleted.
As an alternatvie you could copy all pointers with rtti() == matchRTTI from
matchesList to a new list, e.g. deleteList, use setAutoDelete(true) on this
list and simply clear it.
> }
> }
> //this is the list where are stored pointers to canvas items
> matchesList.clear();
Is this setAutoDelete(true) ?
If not you probably have a memory leak.
> }
>
> Here's the method where I erase item in game :
> void KMatchesView::play()
> {
> // iterator of the list of selected sprites
> QValueList<int>::Iterator it;
> for (it = selectedList.begin(); it !=selectedList.end();it++)
> delete matchesList.at(*it);
You delete the entry in the matchesList here, but you do not remove it from
the list! Do something like
QCanvasItem* match = matchesList.take(*it);
delete match;
Otherwise your clear() method above will try to delete items that already got
deleted (->crash).
> }
> selectedList.clear();
> }
>
> Is there something wrong in these methods ?
> Is there a way to test if a QPtrList exists (like if (matchesList) ...)
I do not understand this question. If a QPtrList is created on the stack it
will always exist. Do you mean whether the list is empty?
> ?
> Thanks.
CU
Andi
More information about the kde-games-devel
mailing list