简体   繁体   English

使用QList元素进行分段错误

[英]Segmentation fault with a element of QList

In my application I have a list of pointer to QFile objects: 在我的应用程序中,我有一个指向QFile对象的指针列表:

QList<QFile*> files

This function adds the elements on the list: 此函数添加列表中的元素:

void MumuServer::openFiles(){
    QDir fileDir(QDir::toNativeSeparators(homeApp.path() + "/file"));
    std::cout << fileDir.path().toStdString() << std::endl;
    if(fileDir.exists()){ // there is files directory in the application home dir
    std::cout << "fileDir exists" << std::endl;
    QStringList filesList = fileDir.entryList();
    for(int index = 0; index < filesList.size(); index++){
        QString fileName = filesList.at(index);
        if(this->blackListFile.contains(fileName)){
            continue;
        }
        QString path = fileDir.path() + "/" + fileName;
        std::cout << path.toStdString() << std::endl;
        QFile file(QDir::toNativeSeparators(path));
        if(file.exists()){
            files.append(&file);
        }
    }
    std::cout << this->files.size() << " files found" << std::endl;
}

After this function the QFile pointers are added on the QList. 在此函数之后,QFile指针被添加到QList上。 But, when I try to manipulate something on a element of the list getting it with the function at(int) a segmentation fault occurs. 但是,当我尝试操作列表元素上的某些东西时,使用(int)函数获取它时会发生分段错误。

Example: 例:

QFile * file = files.at(index);
std::cout << "File size = " << file->fileName() << std::endl;

Somebody are seeing what am I doing wrong? 有人看到我做错了什么?

The objects that you put into your 'files' list have gone out of scope and were destroyed. 放入“文件”列表的对象已超出范围并被销毁。 Use the 'new' operator to allocate them instead. 使用'new'运算符来代替它们。 Be sure to delete them when you are done or you will have a memory leak. 完成后一定要删除它们,否则会有内存泄漏。

    QFile* file = new QFile(QDir::toNativeSeparators(path));
    if(file->exists()){
        files.append(file);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM