Preface
Recently, I learned the shared_pointer in C++11, but things is much complicated then I expected before, in this article, I will go through the an “easy” implementation of binary seach tree, then I will throw out a new concept- weak pointer.
Example
First Case
First, let me implement a tree node using shared pointer
1 |
|
You can see the nodes are deleted safely.
Circle Reference Case
1 | // |
Result:
1 | Contructor |
You can see through output that the three node is not properly deallocated;
Why?????
Let me take a look at what happens during the process. When we reach the end of main function, we will delete the local variable, namely, ptr
, but when we check the reference count of the ptr
, it is 2,(The reason is that the current ptr is being pointed by the Node(2) and Node(5), so the deconstructor of the Node will not be implemented. This is how things work.
How to tackle it ——>weak_pointer
All we need to do is to hand set the type pf parent_ptr as weak_ptr
1 |
|