0

在我的课堂上,当我尝试将任何对象推送到向量 myCache 上时,我得到一个运行时错误。我知道我正在正确初始化向量,并且对为什么会发生这种情况感到困惑。

#ifndef CACHE_H
#define CACHE_H

#include <iostream>
#include "cacheblock.h"
using namespace std;

class Cache
{
  public:
   Cache(int rows, int numWords);
   ~Cache();
   CacheBlock getBlock(int index);

  private:
   vector<CacheBlock> *myCache;
};

#endif

Cache::Cache(int rows, int numWords)
{
   myCache = new vector<CacheBlock>;
   CacheBlock test(rows, 0, 0);
   myCache->push_back(test);

/*
   for (int i = 1; i < rows; i++)
   {
      myCache->push_back(test);
      cout << "inside loop\n\n";
   }
*/
}

缓存块.h:

class CacheBlock
{
  public:
   CacheBlock(int numWords, int newIndex, int tagNum);
   CacheBlock(const CacheBlock &newCacheBlock);
   ~CacheBlock();
   void setData(int numWords, int newIndex, int tagNum);

  private:
   bool valid;
   int index;
   int tag;
   vector<int> *dataWords;
};

任何人都可以帮忙吗?

4

1 回答 1

5

大概有一个有效的复制构造函数CacheBlock

编辑:感谢您发布附加代码。

如果析构函数CacheBlock清除了vector<int> *dataWords删除分配的内容,那么复制构造函数将需要“深度复制” 的向量dataWords。如果没有这个深拷贝,当CacheBlock被复制时,将有两个CacheBlock具有相同指针的vector<int>. 当第一个实例被清理后,第二个实例最终会带有一个指向现在已删除副本的流浪指针。

值得一提的是,正如评论所暗示的那样,为什么vectors<>要从堆中分配它们,如果它们不是从堆中分配的,而仅仅是成员变量,那么这些问题都不会发生。

以机智:

#ifndef CACHE_H
#define CACHE_H

#include <iostream>
#include "cacheblock.h"
using namespace std;

class Cache
{
  public:
   Cache(int rows, int numWords);
   // no longer need a destructor, as the auto-generated one by the compiler suffices
   // ~Cache();
   // potential optimization to return by const reference, rather than by copy
   const CacheBlock& getBlock(int index) const;

  private:
   vector<CacheBlock> myCache;
};

#endif

Cache::Cache(int rows, int numWords)
{
   // no longer need to construct the vector
   // myCache = new vector<CacheBlock>;
   CacheBlock test(rows, 0, 0);
   myCache->push_back(test);
}

缓存块.h:

class CacheBlock
{
  public:
   CacheBlock(int numWords, int newIndex, int tagNum);
   // no longer need a copy constructor
   // CacheBlock(const CacheBlock &newCacheBlock);
   // no longer need a destructor, as the compiler-generated one will suffice
   // ~CacheBlock();
   void setData(int numWords, int newIndex, int tagNum);

  private:
   bool valid;
   int index;
   int tag;
   vector<int> dataWords;
};
于 2011-05-04T21:14:15.437 回答