I am using a QList and I want to iterator though it, but the iterator that i get from it keeps failing, even if I use the auto keyword or not.
for( auto iter = myModel->getList().begin(); iter != myModel->getList().end(); ++iter )
{
if( (*iter)->getList().empty() )
{
if( (*iter)->getData()->getCode() == baseData->getCode() )
return true;
}
}
return false;
Does anyone know why this could be happening? Or is there a different way that I am to use the QList::iterator?
EIDT:
I have noticed another odd thing about this. I do see that the iterator is showing (error)0, and this is odd because it actually contains the data I need.
But if I edit my code to look like this:
QList<T*> tempList = myModel->getList();
for( auto iter = tempList .begin(); iter != tempList .end(); ++iter )
{
if( (*iter)->getList().empty() )
{
if( (*iter)->getData()->getCode() == baseData->getCode() )
return true;
}
}
return false;
then everything works fine. I guess it is a solution, but does anyone know why it needs to be done like this? Or am I just not seeing something very important?
I see two issues with the code.
a)
myModel->getList()returns a copy of your QList declared something like this:you actually should get an access violation. But I don’t know if that’s what happening.
b) If you only rely on what Visual Studio is saying about iter, forget it, its wrong. It just can’t handle the iterator. Allthough the iterator says its (error)0 as an int it will still give you the correct data if dereferenced.
If none of the above is the case please specify what actually goes wrong, is the for loop beeing skipped all together? If so, I’ll edit my answer accordingly.
Best regards
D
EDIT
The reason why it works fine with the temporary List object is following:
The moment you create an iterator with the
begin()method of the list, the list detaches its private data (implicit sharing), meaning it creates a deep copy of itself because you could change the data with that iterator. Without the temporary objectmyModel->getList()creates a temporary object which immediately after the iterator has been created is beeing destroyed. From that moment on the iterator points to nowhere. You might try using theconst iterator, this one should work without detaching the private data hence without the problem.Another approach would be to make your model return the list as a const reference or a pointer.
Another way would be to discard iterators and use the
at()method of the list directly. Makes code more readable in my opinion.