QList 内部的 boost::shared_ptr 会导致分段错误

boost::shared_ptr inside QList leads to segmentation fault

本文关键字:错误 分段 ptr 内部 boost shared QList      更新时间:2023-10-16

我对QList和boost:shared_ptr有一个奇怪的问题。恐怕我无法将问题剥离开来,这就是为什么我稍后会发布wholoe函数的原因。

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

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

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

来自Qt容器文档:

只要 QLinkedList 中的某个项存在,指向该项的迭代器就保持有效,而指向 QList 的迭代器在任何插入或删除后都可能变为无效。