C++ Delete Operator
I'm relatively new to C++ and I have an issue which I 开发者_Python百科really do not understand. My code creates a linked list. It is actually longer than this, but I chopped it down for the purpose of this question.
When I run the code, it adds three nodes and then when it goes to delete the node with the URI b
, it calls the delete
operator and ends up deleting the node, but then it seems to go back to delete
operator (when I step through it) and it kills my whole list.
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
using namespace std;
class CLinkedList
{
protected:
class ip_uri_store
{
public:
string uri, ip;
ip_uri_store* next;
ip_uri_store(const string& URI, const string& IP) {uri = URI, ip = IP, next = NULL;}
};
typedef ip_uri_store* nodeAddress;
nodeAddress head;
void AddNode(const string&, const string&, nodeAddress);
void DeleteNode(const string&, nodeAddress, nodeAddress);
public:
CLinkedList() {head = NULL;}
void AddNode(const string& URI, const string& IP) {AddNode(URI, IP, head);}
void DeleteNode(const string& URI) {DeleteNode(URI, head, head);}
};
void CLinkedList::AddNode(const string& URI, const string& IP, nodeAddress node)
{
nodeAddress temp = new ip_uri_store(URI, IP);
temp->uri = URI;
temp->ip = IP;
temp->next = head;
head = temp;
}
void CLinkedList::DeleteNode(const string& URI, nodeAddress node, nodeAddress behindNode)
{
if(node)
{
if(!node->uri.compare(URI))
node == head ? head = head->next : behindNode->next = node->next;
else
DeleteNode(URI, node->next, node);
delete node;
}
}
int main(int argc, char* argv[])
{
CLinkedList lList;
lList.AddNode("a", "1");
lList.AddNode("b", "2");
lList.AddNode("c", "3");
lList.DeleteNode("b");
return 0;
}
You are calling delete node;
even if the comparison fails (i.e. node->uri != URI
).
if(!node->uri.compare(URI))
{
node == head ? head = head->next : behindNode->next = node->next;
delete node;
}
else
DeleteNode(URI, node->next, node);
Also, the condition seems to be inverted.
First, you should use std::list and avoid reinventing the world. Anyway, if you are stuck to this implementation for some reason :
- temp->uri = URI; and temp->ip = IP; in the AddNode method are useless because the members are already initialized in the constructor of ip_uri_store class.
- the deletion of the head of the list occurs because the 'delete node' should only be done in the case node->uri.compare(URI) in the DeleteNode method.
Again, you should seriously consider using standard classes...
You are calling delete on all the nodes. It needs to be moved inside the conditional so you only delete the nodes that match the URI
if(!node->uri.compare(URI)) {
node == head ? head = head->next : behindNode->next = node->next;
delete node;
} else {
DeleteNode(URI, node->next, node);
}
精彩评论