在我的课堂上,当我尝试将任何对象推送到矢量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
Run Code Online (Sandbox Code Playgroud)
和
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";
}
*/
}
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
据推测,有一个工作的复制构造函数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
Run Code Online (Sandbox Code Playgroud)
和
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);
}
Run Code Online (Sandbox Code Playgroud)
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;
};
Run Code Online (Sandbox Code Playgroud)