質問

In my application I have a list of pointer to QFile objects:

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. But, when I try to manipulate something on a element of the list getting it with the function at(int) a segmentation fault occurs.

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. 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帰属
所属していません StackOverflow
scroll top