我正在尝试实现一个维护链表节点池的池类
虽然分配和释放工作正常,但析构函数会抛出异常。
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;
}
是否是由于堆损坏?
答案 0 :(得分:2)
您分配了一系列员工:
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];
}