C++ std::ifstream因某种原因关闭?

C++ std::ifstream因某种原因关闭?,c++,C++,我试图打开包含文件数据的ifstreams,这些数据以后可以读取。我试图将ifstreams的向量传递到构造函数中,但由于某种原因,当我循环遍历该向量时,所有引用都是关闭的。但是,其他变量(数据流和元流)仍然是开放的 我错过了什么?我来自一个非常重的Java背景,所以我仍然在学习C++ FileStore.h // // Created by Tom on 8/16/2017. // #ifndef CFS_FILESTORE_H #define CFS_FILESTORE_H #inclu

我试图打开包含文件数据的ifstreams,这些数据以后可以读取。我试图将ifstreams的向量传递到构造函数中,但由于某种原因,当我循环遍历该向量时,所有引用都是关闭的。但是,其他变量(数据流和元流)仍然是开放的

我错过了什么?我来自一个非常重的Java背景,所以我仍然在学习C++

FileStore.h

//
// Created by Tom on 8/16/2017.
//

#ifndef CFS_FILESTORE_H
#define CFS_FILESTORE_H

#include <fstream>
#include <list>
#include "ByteBuffer.h"

class FileStore {

private:
    std::ifstream *data_stream;
    std::vector<std::ifstream *> index_streams;
    std::ifstream *meta_stream;

public:
    FileStore(std::ifstream *data, std::vector<std::ifstream *> indexes, std::ifstream *meta);
    ~FileStore() = default;

    int get_type_count();
    ByteBuffer read(int type, int id);
    int get_file_count(int type);

    static FileStore open(std::string &root);
};


#endif //CFS_FILESTORE_H

每个
索引
在其作用域的末尾被销毁,导致指向它们的指针无效

std::vector<std::ifstream *> indexes;
for (int i = 0; i < 254; i++) {
    std::ifstream index(root + "main_file_cache.idx" + std::to_string(i));
    if (!index.good())
        break;

    indexes.push_back(&index);
} // index is destroyed here
或者更好地使用
std::vector
std::make_unique

当您从
open
返回时,
meta
data
可能会遇到同样的问题

    std::ifstream index(root + "main_file_cache.idx" + std::to_string(i));
这将构造一个
std::ifstream
对象。它使用自动作用域声明

    indexes.push_back(&index);
}
这会将指向
std::ifstream
的指针推送到
索引
向量中,但是由于
索引
的自动作用域随后立即结束,因此
索引
对象会立即销毁,并关闭其相应的文件。您在内部循环的自动作用域中声明了这个
std::ifstream
对象。因此,对象在循环结束时被销毁

随后的代码尝试取消对这些指针的引用,这些指针存储在
索引
向量中,现在这些指针都是悬空指针。这会导致未定义的行为

此外,
索引
向量按值传递,这导致向量被复制,这增加了混淆

你需要重新阅读C++书中的以下章节:

    <> >解释C++中的自动范围和动态范围如何工作的一章
  • 本章解释了通过引用传递函数参数和通过值传递函数参数之间的区别,以及这意味着什么


每个
索引都在其作用域的末尾被销毁,导致指向它们的指针无效感谢您的响应,这就是我提出的解决方案。到目前为止,这似乎给了我想要的输出
std::vector<std::ifstream *> indexes;
for (int i = 0; i < 254; i++) {
    std::ifstream* index = new std::ifstream(root + "main_file_cache.idx" + std::to_string(i));
    if (!index->good())
        break;

    indexes.push_back(index);
}
    std::ifstream index(root + "main_file_cache.idx" + std::to_string(i));
    indexes.push_back(&index);
}