For loop iterating over empty container enters the loop anyway?
-
wrote on 10 Dec 2013, 10:54 last edited by
I have a QList<QModelIndexes> container that I iterate over. Sometimes it is of size zero. When it is of size zero, an attempt it made to dereference the iterator and a segFault is thrown. Looking at my code, I think that shouldn't happen; when the QList<QModelIndexes> is of size zero, the entire for loop should be skipped. My code is below. I've got the debug of a segFault on screen in front of me and candidateIndices clearly is of size zero, but the segfault is inside the for loop at that first line where I dereference the iterator.
I've done this just the way I would for a std C++ container class. Have I massively misunderstood this?
@ auto candidateIndices = ui->treeView->model()->match(ui->treeView->model()->index(0, 1), Qt::DisplayRole, valueToMatch, -1, Qt::MatchExactly);
for (auto candidatesIterator = candidateIndices.begin(); candidatesIterator != candidateIndices.end(); ++candidatesIterator) { QModelIndex candidateIndex = *candidatesIterator;@
-
wrote on 10 Dec 2013, 12:19 last edited by
Well, I think it is because of "auto" type.
If you know exactly what type candidateIndices should be (seems you know) then declare it as that type. Maybe "auto" dosn`t work well with empty container. -
wrote on 10 Dec 2013, 12:21 last edited by
Hi,
A for loop is very much the same as a
@
do {
// Something here
} while (1);
@
So, yes, the condition to test is done at the end of the for loop! Not at the first beginning. So when the container is empty, the loop will crash!
It is better to use QList::const_iterators btw. These are designed to handle QList items in a list etc.
Use the list.isEmpty() == false and then start the for loop. Or create a while/do loop, which in basic is the same.
Or if you really like Qt, use the foreach. That will not run when the list is empty, I believe?!
Greetz -
wrote on 10 Dec 2013, 12:30 last edited by
I think for empty container begin() == end() and for loop does nothing.
In this case problem is auto initialisation with empty container. For me it seems auto candidateIndices is not container.
I am using many times loop with iterators and never got problem with empty container. But I declare exact type, not auto. -
wrote on 10 Dec 2013, 12:34 last edited by
And "for (i=0; i < x; ++i)" loop is rather as
@
i=0;
while (i < x)
{
//something
++i;
}
@
5/5