delete operator in destructor

class MapNode {
public:
string key;
V value;
MapNode* next;

MapNode(string key, V value) {
this->key = key;
this->value = value;
next = NULL;
}

~MapNode() {
delete next;
}
};

How does the delete next works and how it deletes the whole list instead it should delete the value to which next is pointing
As formatted and tweaked, then:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <string>

template<typename V>
class MapNode {
	std::string key;
	V value {};
	MapNode* next {};

public:
	MapNode() = default;
	MapNode(const std::string& key_, const V& value_) : key(key_), value(value_) {}

	MapNode(const MapNode&) = delete;
	MapNode(MapNode&&) = delete;
	MapNode& operator=(MapNode) = delete;

	~MapNode() {
		delete next;
	}
};


How is MapNode to be used? As it stands, next member is not used. Is this supposed to be a node for say an associative container (like std::map)?
Last edited on
How does the delete next works and how it deletes the whole list instead it should delete the value to which next is pointing
Try running the code in a debugger, or add print statements to the destructor, with some driving logic in main.

When it calls delete next, it dereferences next (if not null), and then triggers the destructor for next, which then recursively calls delete on the next node's next, and so on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Example program
#include <iostream>
#include <string>

template<typename V>
class MapNode {
  public: // public to access next
	std::string key;
	V value {};
	MapNode* next {};

	MapNode() = default;
	MapNode(const std::string& key_, const V& value_) : key(key_), value(value_) {}

	MapNode(const MapNode&) = delete;
	MapNode(MapNode&&) = delete;
	MapNode& operator=(MapNode) = delete;

	~MapNode() {
	    std::cout << "Deleting node with value " << value << '\n';
		delete next;
	}
};

int main()
{
    {
        MapNode<int> node("answer", 42);
        node.next = new MapNode<int>("nintendo", 64);
        node.next->next = new MapNode<int>("blocks", 17398);            
    } // destructor will be called automatically
    
    std::cout << "Done.\n";
}


Personally, I like to avoid the recursive nature in this manner, and will instead have a type like "Map" that aggregates a group of MapNodes, and then just iterates through them in the Map's destructor.
Last edited on
Topic archived. No new replies allowed.