Problems with bad_weak_ptr, shared_from_this and constructors

A while ago I wrote this post:
http://www.cplusplus.com/forum/general/265809/

And then because of the problems with that project, I moved on to work on another project and forgot about this (and didn't know threads in here could be archived, or after how long this would happen). Recently, I've been trying to get this to work again, replaced shared_ptr with weak_ptr as suggested in the previous thread.

As I mentioned in that thread, I'm trying to implement Dancing Links. This means that each Node has four neighbours, that MUST be initialized to point to the Node itself, for Algorithm X that DLX is made for, to work.

Since then I've read up on enable_shared_from_this and why it caused a bad_weak_ptr as it still does. I've found out that shared_from_this requires there to exist a shared_ptr to the object already, and that because of this, it's not possible to use shared_from_this() in a constructor, as I do in the code below.

So I've been thinking about ways to circumvent this. From the knowledge I've acquired, it seems to me that it should work to add a second constructor and a weak_ptr to the Node itself, that is constructed using this second constructor, which will be empty. This is demonstrated in the code, though this means it won't compile.

When I try this approach, I unfortunately get the same old bad_weak_ptr exception, and I am at a loss for why now. So I'm hoping someone can tell me how to make this current design work, if not with a weak_ptr to a Node.

You see, I cannot change this design. It is how DLX works. I can't just make the four directional pointers be null_ptr, it is required for them to point to the object they're part of, for the linking to work properly. And after finding out how much unnecessary memory is used when not using pointers, I've got to stick to using some sort of smart pointers, rather than having the variables be Node variables instead.

Here is my updated code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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();
			Node(bool first);
			virtual ~Node();

			weak_ptr<Node> self;
			weak_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
16
17
#include "Node.hpp"

namespace dlx
{
	Node::Node()
	{
		self = make_shared<Node>(true);

		up = shared_from_this();
		down = shared_from_this();
		left = shared_from_this();
		right = shared_from_this();
	}

	Node::~Node(bool first) {}
	Node::~Node() {}
} /* namespace dlx */
I'm familiar with the algorithm.

However, as is the case with most linked structures, a node does not own its neighbors, so an attempt to use shared_ptr in this case is fundamentally wrong.
Topic archived. No new replies allowed.