首页 > 解决方案 > 类中 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对象内访问。这里的任何帮助将不胜感激。

标签: c++segmentation-faultifstream

解决方案


您有两个名为 的不同变量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);

推荐阅读