Node* Node::insertAllPrefixes(constdouble *pattern, constint pattern_size, constint l){
//l corresponds to the discretization level
count += 1;
if (pattern_size == 0) returnthis;
constdouble c = (double)floor(pow(2,l)*pattern[0]);
Node* &son = this->sons[c];
if ( son == NULL) {
son = new Node(this,c);
}
return son->insertAllPrefixes(pattern+1, pattern_size-1,l);
}
Yes, I do create 'son' via new but I don't delete it because once filled-up Node* becomes a tree I traverse in some other class for other calculations.
here's my destructor:
1 2 3 4 5 6 7 8 9 10
Node::~Node(){
if (sons.empty()) return;
map<int,Node*>::iterator it;
for (it = sons.begin(); it!=sons.end(); it++ ) {
delete(it->second);
}
}
So, I'm creating a reference "son" to refer to sons[c] (which is of type Node*), and if I haven't seen c before (so that sons[c] doesn't exist) I create a new son with value c and (update this Node's map<int,Node*>).
Yes, I do create 'son' via new but I don't delete it
They are deleted in the destructor. You have to delete the root node once you no longer need the tree.
If you don't, you shouldn't be surprised that the tool you're using tells you there is a memory leak.
I thought that you've got a non-directed graph. So A is neighbour of B and B is neighbour of A.
1 2 3
for (it = sons.begin(); it!=sons.end(); it++ ) {
delete(it->second);
}
When you destruct a node, you destruct its neighbours first. A will destroy B.
But, as A is neighbour of B, it will try to delete it first.
The destructor will be calling each other, infinite recursion, causing stack overflow.
But if you've got a tree, then you can use composition. std::map<int,Node> sons;
just don't use operator[] as you don't have a default constructor (replace it with find and insert)