I am implementing my own version of Dancing Links, a 2D linked list. Dancing Links is based on Nodes that refers to their four neighbours. To do this, I need to implement those neighbours as shared_ptr<Node>.
In the constructor, I need all four neighbours to point to the Node itself, thus my Node class inherits enabled_shared_from_this, and I then get a shared_ptr by using shared_from_this().
But the problem with this is that I have discovered that shared_from_this() only works if there's already a pointer (shared_ptr presumably) that points to that Node.
I'm not really sure how to go about solving this, since the neighbours are initialized in the constructor by necessity. So I wanna ask, how could I solve this problem with needing a shared_ptr before invoking shared_from_this?
There are two additional concerns about the use of shared_ptr in linked structures:
1. Ownership cycles create memory leaks: if a owns b and b owns a, both resources will wait to be destroyed until the other is destroyed.
2. When a list node is destroyed (assuming no ownership cycles) shared_ptr's destructor is called recursively. If the ownership chain is long enough, destruction may overflow the stack.
But the problem with this is that I have discovered that shared_from_this() only works if there's already a pointer (shared_ptr presumably) that points to that Node.
can you explain a bit in more detail why there must be existing shared_ptr? what is the error otherwise?
Otherwise, shared_ptr will not work very well for this concept as mentioned by mbozzi, you will definitely need to redeclare nodes in class Node as std::weak_ptr to avoid memory leak.