1

i have a strange problem with QList and the boost:shared_ptr. I'm afraid i am not able to strip the problem apart, that's why i will post the wholoe function later on.

What i want to do: I have a list (_fileList) which stores boost::shared ptrs to QFile Objects. The files are XML files. Than i want to parse this file and resolve all includes which means adding the files specified by the include tag also to the _fileList and scanning them for further include tags. The code works fine when resolving 3 includes (in my small test there is only one include per file). The third time the line boost::shared_ptr file(*iter); leads to a segmentation fault. I would be glad if anyone of you can help me or give me hints how i can find this bug.

void XmlParser::expandIncludes()
{
//search all files already in the file list for include tags, if any new are found append this file to the file list
    QList<boost::shared_ptr<QFile> >::iterator iter = this->_fileList.begin();
    while(iter!= this->_fileList.end())
    {
        boost::shared_ptr<QFile> file(*iter);
        QDomDocument doc("activeFile");
        if (!file->open(QIODevice::ReadOnly)){
            return;
        }
        if (!doc.setContent(&(*file))) {
            file->close();
            return;
        }
        file->close();
        QDomElement docElem = doc.documentElement();

        QDomNode n = docElem.firstChildElement("include");
        while(!n.isNull()) {
            QDomElement e = n.toElement(); // try to convert the node to an element.
            if(!e.isNull()) {
               QString nextFile = e.text();
               QString nextFileAbsolutePath = this->_workingDir.absolutePath() +"/"+nextFile;
               boost::shared_ptr<QFile> newFileObject(new QFile(nextFileAbsolutePath));
               this->_fileList.append(newFileObject);

            }
            n = n.nextSiblingElement("include");
        }
        doc.clear();
        iter++;
    }
}
4

1 回答 1

2

Iterators pointing to elements in a QList becomes invalid after you insert new elements into the list. You could use a QLinkList instead.

From the Qt Container docs:

Iterators pointing to an item in a QLinkedList remain valid as long as the item exists, whereas iterators to a QList can become invalid after any insertion or removal.

于 2012-08-15T00:48:26.320 回答