Is this the right way, to use boost::shared_ptr for the nodes left and right and boost::weak_ptr for the root. I know shared is an overkill. I will need this for later.
class Node, 2 sons shared ptr
class Node
{
public:
boost::shared_ptr<Node> left;
boost::shared_ptr<Node> rigth;
int nVal;
Node();
Node(int);
~Node();
Node getVal(void);
void setVal(int);
};
Node::Node()
{
cout << "creating node empty" << endl;
nVal = 0;
left.reset();
rigth.reset();
}
Node::~Node()
{
cout << "entering destructor" << endl;
}
Node::Node(int n)
{
cout << "creating node with value" << endl;
nVal = n;
left.reset();
rigth.reset();
}
Node Node::getVal(void)
{
cout << "returning value" << endl;
return this;
}
void Node::setVal(int n)
{
cout << "setting value" << endl;
nVal = n;
}
class tree, weak ptr
class Tree
{
public:
boost::weak_ptr<Node> root;
Tree();
~Tree();
void findParent(int n, int &found, Node &parent);
void add(int n);
void post(boost::weak_ptr<Node> q);
void del(int n);
};
Tree::Tree()
{
root = NULL;
}
You should not use a weak pointer for the node like this. A weak pointer means that the object may be deleted even if there are still weak pointers available for the object, if no other weak pointers to it exists.
So in your case you have one weak pointer to the root and no shared pointer. In this situation the root will be deleted, since no shared pointers are keeping it alive and all of the tree will be gone.
The general rule is, that a shared pointer should be used for ownership relationships. The Tree definitely owns the root of itself. Weak pointer on the other hand should be used for back pointers to direct or indirect parents, to break out of circles. So if you had nodes pointing back to root, this would be a place to use weak pointer.
The best way to make sure is to first try to use shared pointers, and pay attention not to build any circles in the dependencies. Only when you have to break a circle change a shared pointer to a weak pointer based on the ownership/backpointer difference.