其他分享
首页 > 其他分享> > C删除不起作用?

C删除不起作用?

作者:互联网

我遇到了删除和析构函数的问题(我确信我在这里犯了一个愚蠢的错误,但是到目前为止还没能弄明白).

当我逐步进入析构函数,并尝试在指针上调用delete时,消息显示“无法访问地址某个地址的内存”.

相关代码是:

/*
 * Removes the front item of the linked list and returns the value stored
 * in that node.
 *
 * TODO - Throws an exception if the list is empty
 */
std::string LinkedList::RemoveFront()
{
    LinkedListNode *n = pHead->GetNext(); // the node we are removing
    std::string rtnData = n->GetData(); // the data to return

    // un-hook the node from the linked list
    pHead->SetNext(n->GetNext());
    n->GetNext()->SetPrev(pHead);

    // delete the node
    delete n;
    n=0;

    size--;
    return rtnData;
}

/*
 * Destructor for a linked node.
 *
 * Deletes all the dynamically allocated memory, and sets those pointers to 0.
 */
LinkedListNode::~LinkedListNode()
{
    delete pNext; // This is where the error pops up
    delete pPrev;
    pNext=0;
    pPrev=0;
}

解决方法:

您似乎要从析构函数中删除列表的下一个和上一个节点.其中,如果pNext和pPrev是LinkedListNode *,则表示您递归删除整个列表:-(

试试这个:

std::string LinkedList::RemoveFront()
{
    LinkedListNode *n = pHead->GetNext(); // the node we are removing
    std::string rtnData = n->GetData(); // the data to return

    // un-hook the node from the linked list
    pHead->SetNext(n->GetNext());
    n->GetNext()->SetPrev(pHead);

    n->SetNext(0);
    n->SetPrev(0);
    // delete the node
    delete n;
    n=0;

    size--;
    return rtnData;
}

LinkedListNode::~LinkedListNode()
{
}

(实际上你甚至不需要将prev和next指针重置为0,因为你要删除节点.我将这些语句留下来因为它们至少使节点处于一致状态,这是个好主意.如果您稍后改变您的内存管理策略并决定存储未使用的节点以供以后重用,则可能会有所不同.)

标签:c,destructor,delete-operator
来源: https://codeday.me/bug/20190827/1740989.html