I am working on code to create a type of circular linked list. I have a class CLNode for the actual nodes of the list and a second class CLPtr for pointers to the nodes. The node class is entirely private, and all access must be done through the pointers. The nodes contain a shared pointer to an integer which gives the number of "CLPtr"s that point to an element of the list. Whenever CLPtr's constructor and destructor keep this number up to date.

If after CLPtr's destructor notices that it is the last CLPtr pointing to the list, it "delete"s the node. The node's destructor then recursively destroys the list. If the previous link is nonnull, it sets its "next" link to null, then if the next link is not null, it sets the next link's previous link to null and "delete"s it. The code for the destructor follows:

Code:
template <class T>
CLNode<T,U>::~CLNode()
{
     cout<<"Deleting node: "<<*this<<endl;
     if(links[1-direction]!=0)
     {
         cout<<"root"<<endl;
         getPrevious().links[direction]=0;
     }
     if(links[direction]!=0)
     {
         getNext().links[1-direction]=0;
         cout<<"about to delete "<<getNext()<<endl;         
         delete links[direction];
         cout<<"returning to "<<*this<<endl;
     }
     cout<<"finished "<<*this<<endl;

}
If the list is 1,2,3,4 and the pointer points to 3 it prints:

Code:
Destroying CLPTR.  1 CLPTRs remain for this CL list.
Destroying CLPTR.  0 CLPTRs remain for this CL list.
about to delete 3
Deleting node: 3
root
about to delete 4
Deleting node: 4
about to delete 1
Deleting node: 1
about to delete 2
Deleting node: 2
finished 2
returning to 1
finished 1
returning to 4
finished 4
______________________
finished 3
At the line, a popup sometimes comes up that says "LinkedList.exe has stopped working". Any suggestions for why this happens? Is there a better way to do this?

I'm working on a minimal working example to post.