How to use shared_from_this without having a pointer?

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?

Here's some example code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef DLX_NODE_HPP_
#define DLX_NODE_HPP_

#include <memory>
using namespace std;

namespace dlx
{
	class Node : public enable_shared_from_this<Node>
	{
		public:
			Node();
			virtual ~Node();

			shared_ptr<Node> up, down, left, right;
	};
} /* namespace dlx */

#endif /* DLX_NODE_HPP_ */ 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "Node.hpp"

namespace dlx
{
	Node::Node()
	{
		up = shared_from_this();
		down = shared_from_this();
		left = shared_from_this();
		right = shared_from_this();
	}

	Node::~Node()
	{}
} /* namespace dlx */
Last edited on
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.
Topic archived. No new replies allowed.