c++ - 类中 ifstream 指针的分段错误
问题描述
我在一个类(File
下面的代码中的类)中打开一个 ifstream,然后使用一个单独的类从 ifstream(Record
下面的类)中读取一条记录。但是,在创建初始对象后,当我从子类访问 ifstream 时,代码会出现段错误。
代码:
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
class Record {
std::ifstream * stream;
public:
Record(std::ifstream * infile) : stream(infile) {};
int position() { return (int) stream->tellg(); }; // function errors when run from main()
};
class File {
std::ifstream stream;
public:
File(std::string path) {
std::ifstream stream(path, std::ios::binary);
records.push_back(Record(&stream));
// I can call record.position() without error after creation
std::cout << "position after creation: " << records[0].position() << std::endl;
};
std::vector<Record> records;
};
int main() {
File file("/home/jmcrae/test.txt");
file.records[0].position(); // calling this segfaults
}
// gcc -lstdc++ -std=c++11 test.cpp
我很确定 ifstream 没有在 Record 类中初始化,但我不明白为什么不这样做。Record
在对象内创建 a File
,然后调用position()
可以正常工作,但前提是在File
对象内访问。这里的任何帮助将不胜感激。
解决方案
您有两个名为 的不同变量stream
: 的成员属性File
和 的构造函数的局部变量File
。在File
的构造函数中,初始化局部变量流,然后将指向该对象的指针传递给 的构造函数Record
。一旦File
的构造函数退出,这std::ifstream
就会超出范围。Record
当您尝试将其指针解析为不再存在时,您编写代码段错误std::ifstream
。
要解决此问题,请替换该行
std::ifstream stream(path, std::ios::binary);
和
stream = std::ifstream(path, std::ios::binary);
推荐阅读
- r - R 光栅错误:无法从此文件创建 RasterLayer 对象。(文件不存在)
- oracle - Oracle 转换为东部时区
- javascript - 使用颜色选择器更改 React 中下拉项的颜色
- javascript - 什么是函数 createServer(requestListener?:RequestListener):server?
- bash - Ubuntu 18.04 Bash Shell 脚本上的漏洞检查
- c# - 分离程序和设计逻辑(C# Winforms项目结构)
- eventbrite - Eventbrite 事件 API 现在返回 404
- python - Tkinter 框架使用 create_window 选项等效于展开
- javascript - 在不更改配置的情况下获取过去的 import/no-named-as-default lint 错误
- sql - 如何用 0 填充 null 并使用 spark `pivot` 累积`count`?