矢量超出范围

Vector going out of scope

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

所以我的结构向量超出范围时遇到了问题。我不知道为什么。我以前使用过矢量,但由于某种原因,这不起作用。我看了几个论坛,尝试了几种不同的方法来解决这个问题。

构造函数和DirectMap方法都在main中被调用。我希望向量保持在两种方法的作用域中。这可能吗?感谢Alot的帮助!

以下是我在头文件中声明的方式:

struct input
{
    bool dirtyBit;
    int statusBit; //0 not in cache, 1 in cache, 2 in 2nd cache
    bool writeStatus; //write = 1 read = 0
    int address;
    int indivBlockIndex;
    int indivBlockOffset;
};
    class Cache
    {
    public:
        vector<input *> dataBase;
        Cache(string);
        ~Cache();
        void DirectMapped(int, int);
    };

以下是我如何使用它:

Cache::Cache(string infile)
{
    ifstream in(infile);
    string readWriteStatus;
    int Addr;
    while (in >> readWriteStatus >> hex >> Addr)
    {
        input *contents;
            contents = new input;
        contents->dirtyBit = false;
        contents->statusBit = 0;
        dataBase.push_back(contents);   
    }
}
Cache::~Cache(){}
void Cache::DirectMapped(int cacheSize, int blockSize)
{
    //initial stats needed
    int blockCount = cacheSize/blockSize; //number of total blocks
    //clear out the cache
    for (int i = 0; i <= dataBase.size(); i++)
        dataBase[i]->statusBit = 0;
//other irrelevent stuff after this
}

再次感谢你抽出时间来帮助我。

问题是,您在向量中存储指向input结构的指针,但从未使它们指向任何位置。一个简单的解决方案可能是更改

input *contents;

input *contents = new input;

然而,管理一个原始点向量会产生各种令人讨厌的后果。在您的特定情况下,我认为没有理由首先保留指针向量。只需使用

vector<input> dataBase;

并存储实际结构。