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";
   }
*/
}

CacheBlock.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への同じポインタを持つ の2 つのインスタンスが存在しますvector<int>。最初のインスタンスがクリーンアップされると、2 番目のインスタンスは、削除されたコピーへの浮遊ポインターになります。

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);
}

CacheBlock.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 に答える