在我的代碼中,我製作了一個指向動態分配的類對象的節點列表,我似乎無法弄清楚如何確保我可以自由刪除特定節點時的內存。如何從鏈接列表上的節點釋放內存分配的類
//create temporary node
node *temp = new node;
//create the pointer to the class
Dog *thisDog = new Dog(age, name);
//set the next pointer to NULL (points to nothing)
temp->next = NULL;
//set first value in list to temp
head = temp;
//set last value to temp
last = temp;
當我刪除節點時,類對象中的析構函數是否會幫我處理這個問題?還是我的節點刪除功能中我應該包括一些諸如下列:
//delete one element
delete *&thisDog;
delete head;
//set the head and last pointer to NULL, point to nothing
head = NULL;
last = NULL;
這裏是我的節點結構:
struct node
{
Dog *thisDog;
node *next;
};
'delete *&thisDog;' - 那個單獨應該是一個指標,可能會發生相反的情況,因爲'delete thisDog;'應該足夠了。並且你打算把'thisDog'放在列表中的某處,因爲這不會發生在你的發佈代碼中。 – WhozCraig
請用相關內容更新您的*問題*。 – WhozCraig