对于我的家庭作业,我需要制作从Deque中添加(附加(和删除(服务(节点的方法。但是,当尝试为最后一个节点提供服务时,我遇到了内存泄漏,因为我不知道如何检索不再用于系统的节点。 下面是该方法的代码。
void Deque::serveAtRear(int &x)
{
if(empty())
{
cout << "Fila Vazia" << endl;
exit(0);
}
else
{
DequePointer q; //Pointer before p
q = head; //q starts at the deque's head
p = head->nextNode; //Pointer for the next node
if(q->nextNode==NULL) //If there's only one node
{
x = q->entry; //x will receive the value of the removed node to print it afterward
head = tail = NULL;
delete p; //I don't know if I'm using the "delete" right
}
else
{
while(p->nextNode != NULL)
{
p = p->nextNode;
q = q->nextNode;
if(p->nextNode==NULL)
{
q->nextNode=NULL;
}
}
x = p->entry;
delete p->nextNode;
}
delete q->nextNode;
}
}
要添加节点,我有此方法:
void Deque::appendAtFront(int x)
{
if(full())
{
cout << "FULL" << endl;
exit(0);
}
else
{
p = new DequeNode;
p->entry=x;
if(p == NULL)
{
cout << "Can't insert" << endl;
exit(0);
}
else if(empty())
{
head = tail = p;
p->nextNode=NULL;
}
else
{
p->nextNode=head;
head = p;
}
}
}
我也不能使用"deque"lybrary
如何避免泄漏的通用答案是:避免手动分配内存。
例如,您可以使用智能指针,例如std::unique_ptr
,而不是打电话new DequeNode
打电话给std::make_unique<DequeNode>()
.然后,编译器将指出需要调整代码的地方,因为您将限制自己,以便每个DequeNode同时仅由一个unique_ptr拥有。示例弹出函数(其中head
和DequeNode.next
uniuque_ptrs(基于您的 serveAtRear:
if (!head)
{
return;
}
DequeNode* q; //Pointer before p
DequeNode* p; //will be tail eventually
q = head.get(); //q starts at the deque's head
p = q->next.get(); //Pointer for the next node
if(!p) //If there's only one node
{
x = q->entry; //x will receive the value of the removed node to print it afterward
head.reset(); // hear we release DequeNode pointed by head
}
else
{
while(p->next)
{
q = p;
p = q->next.get();
}
x = p->entry;
q->next.reset(); // here we release tail (i.e. p)
}
当然,推动的实施需要采用太:)。