我正在尝试实现一个池类,该池类维护一个链接列表节点池
尽管分配和释放工作正常,但析构函数将引发异常。
class Pool {
public:
Pool ();
~Pool ();
tEmployee *GetFromPool (void);
void GiveToPool (tEmployee * pNode);
void PrintPoolSize ();
private:
int vTop;
tEmployee *vPool;
tEmployee *vDeleted;
};
这里是功能的实现
Pool::Pool ()
:vTop (0), vDeleted (NULL)
{
vPool = new tEmployee[MAX_POOL];
}
tEmployee* Pool::GetFromPool (void)
{
if (vDeleted) {
tEmployee * temp = vDeleted;
vDeleted = vDeleted->next;
return temp;
}
if (vTop == MAX_POOL) {
vPool = new tEmployee[MAX_POOL];
vTop = 0;
}
return vPool + vTop++;
}
void Pool::GiveToPool (tEmployee * pNode)
{
pNode->next = vDeleted;
vDeleted = pNode;
}
Pool::~Pool ()
{
tEmployee *curr = vDeleted;
tEmployee *next = 0;
while (curr) {
next = curr->next;
delete curr; //This line is throwing exception on the second iteration of the loop
curr = next;
}
delete [] vPool;
}
是由于堆损坏吗?
最佳答案
您分配了一组员工:
vPool = new tEmployee[MAX_POOL];
然后错误地尝试分别删除它们:
delete curr; // Don't do this
在正确删除数组之前:
delete [] vPool;
通常,每个
new
必须与一个delete
匹配。您没有单独new
雇员,所以不要单独删除他们。您还需要维护一个指向所有分配数组的指针的列表,以便可以在析构函数中将它们全部删除。目前,您泄漏了所有这些,除了您分配的最后一个。我建议类似的东西:
std::vector<tEmployee *> vPool; // store all allocated blocks
tEmployee* GetFromPool() {
if (vDeleted) {
tEmployee * temp = vDeleted;
vDeleted = vDeleted->next;
return temp;
}
if (vTop == MAX_POOL) {
vPool.push_back(new tEmployee[MAX_POOL]); // add new block to collection
vTop = 0;
}
return vPool.back() + vTop++;
}
~Pool() {
for (size_t i = 0; i < vPool.size(); ++i)
delete vPool[i];
}
关于c++ - 池类抛出错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8346914/