确保文件名不会超出范围
Make sure file name doesn't go out of scope
我想选择一个文件并将文件名存储为我的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
。如果fileName
是char*
,那么你是对的: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字符集以外字符的文件。
一般我能想到三种可能的解决方案:
- 复制对象
- 使用引用计数
- 移动对象
对于给定的库,我会选择最容易使用的
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 从命令行c++发送文本文件名
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 错误:未在此范围内声明'reverse'
- 正在将指针转换为范围
- 使用std::transform将一个范围的元素添加到另一个范围中
- 在基于范围的for循环中使用结构化绑定声明
- 如何计算数据类型的范围,例如int
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 在C++中查找范围的长度
- 如何设置一个范围来提取我想要获得的信息
- 并行用于C++17中数组索引范围内的循环
- 为左值和右值的包装器实现C++范围
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 超出范围时使用对象
- 重命名两个目录中的文件名,如果它们之间的某些字符匹配 - 矢量下标超出范围
- 确保文件名不会超出范围