For loop iterating over empty container enters the loop anyway?

  • 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;@

  • 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.

  • 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?!

  • 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.

  • And "for (i=0; i < x; ++i)" loop is rather as
    while (i < x)

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.