memory leaks question

J

Jason

Hi,

I have a class representing a tree-like structure called Node. Each Node
contains a vector of pointers to other nodes ie stl::vector<Node*>. The
Node class itself contains a destructor method to delete all the nodes
within its vector as below:

Node::~Node() {
for(vector<Node*>::iterator it = outedges.begin(); it != outedges.end();
++it)
delete *it;
}

All the nodes were taken from dynamic memory using 'Node* newnode = new
Node; node->add(newnode);' etc, except the initial Root node, which is just
an attribute of another class. My question is, if I call the destructor
method on just the root node, what will happen to all the nodes pointed to
by its sub-nodes amd the sub-nodes sub-nodes etc. Will the entire tree be
deleted or will it leave pointers with no owner, meaning that I should
traverse the entire tree, deleting all leaf nodes, then moving back up to
finally delete the root? I'm hoping that I can just destroy the root and
then everything else will be ok.

Thanks for your help
Jason.
 
J

Jason

Sheesh, I just read you dont call destructors automatically, therefore, now
the destructor is defined, is it all taken care of?
 
K

Karl Heinz Buchegger

Jason said:
Hi,

I have a class representing a tree-like structure called Node. Each Node
contains a vector of pointers to other nodes ie stl::vector<Node*>. The
Node class itself contains a destructor method to delete all the nodes
within its vector as below:

Node::~Node() {
for(vector<Node*>::iterator it = outedges.begin(); it != outedges.end();
++it)
delete *it;
}

All the nodes were taken from dynamic memory using 'Node* newnode = new
Node; node->add(newnode);' etc, except the initial Root node, which is just
an attribute of another class. My question is, if I call the destructor
method on just the root node, what will happen to all the nodes pointed to
by its sub-nodes amd the sub-nodes sub-nodes etc. Will the entire tree be
deleted or will it leave pointers with no owner, meaning that I should
traverse the entire tree, deleting all leaf nodes, then moving back up to
finally delete the root? I'm hoping that I can just destroy the root and
then everything else will be ok.

You don't need to destroy the root node, it will be done automatically
when the object that contains the root node gets destroyed.
But then the dtor kicks in and destroys all of the roots children
which by themself will destroy all there children etc. until the
whole structure is deleted.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top