确保文件名不会超出范围

Make sure file name doesn't go out of scope

本文关键字:范围 文件名 确保      更新时间:2023-10-16

我想选择一个文件并将文件名存储为我的QT形式的char *成员变量。我有如下

void MainWindow::SelectVolFile(){
    QString qFileName = QFileDialog::getOpenFileName(this, 
        tr("Select VOL file..."), QDir::currentPath(), tr("Files (*.VOL)"));
    if (!qFileName.isEmpty()){
        QByteArray byteFileName = qFileName.toLatin1();
        this->fileName = byteFileName->data();
    }
}

然而,我认为一旦这个函数返回,byteFileName->data()就超出了作用域。解决这种情况的好方法是什么?我不确定应该把哪个变量放到堆上

这在很大程度上取决于this->fileName。如果fileNamechar*,那么你是对的:byteFileName超出了作用域,byteFileName->data()将被释放,这导致一个悬空指针,this->fileName

解决这种情况的最简单方法是将this->fileName的类型设置为QString, std::string或实际复制byteFileName->data()内容的其他类型。

您可以将this->filename定义为QString,它将工作。

如果你想使用char*作为文件名,你应该使用new在该函数中分配内存,并将byteFileName->data()复制到它。

this->filename = new char[strlen(byteFileName->data())+1];
strcpy(this->filename, byteFileName->data());

为了最好,不要将qFileName转换为其他任何内容(fileName字段必须更改为QString):

void MainWindow::SelectVolFile(){
    QString qFileName = QFileDialog::getOpenFileName(this, 
        tr("Select VOL file..."), QDir::currentPath(), tr("Files (*.VOL)"));
    if (!qFileName.isEmpty()){
        this->fileName = qFileName;
    }
}

您的代码将无法正确处理文件名中包含latin1字符集以外字符的文件。

一般我能想到三种可能的解决方案:

    复制对象
  • 使用引用计数
  • 移动对象

对于给定的库,我会选择最容易使用的