QList中的boost :: shared_ptr导致分段错误

时间:2012-08-15 00:24:42

标签: c++ qt boost smart-pointers

我对QList和boost:shared_ptr有一个奇怪的问题。我担心我无法将问题分开,这就是为什么我稍后会发布wholoe功能的原因。

我想做什么:我有一个列表(_fileList),它将boost :: shared ptrs存储到QFile对象。这些文件是XML文件。比我想解析这个文件并解决所有包含这意味着将include标签指定的文件也添加到_fileList并扫描它们以获取更多包含标签。解析3包含时代码工作正常(在我的小测试中,每个文件只有一个包含)。第三次排队 boost :: shared_ptr文件(* iter);导致分段错误。 如果你们中的任何人可以帮助我或者告诉我如何找到这个错误,我会很高兴。

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++;
    }
}

1 个答案:

答案 0 :(得分:2)

将新元素插入列表后,指向QList中元素的迭代器将变为无效。您可以使用QLinkList。

来自Qt Container文档:

只要项目存在,指向QLinkedList中项目的迭代器仍然有效,而QList的迭代器在插入或删除后可能变为无效。