Debug assertion failure – C++, using smart pointers

I have been trying to debug this for a while now without any luck. I was hoping to get some help here. Apologies if my question isn’t relevant or something, I’m new.

So basically what I have is:

#include <iostream>

template<typename T> class Node {
    using NodePtr = std::shared_ptr<Node<T>>;
private:
    Node() {}
    T value{};
    NodePtr parent;
    NodePtr child;
public:
    Node(const T& value) : value{ value } {}
    Node(const T& value, NodePtr child) : Node(value)
    {
        this->child = child;
        if (child != NULL)
        {
            //problem here?  
            child->parent = NodePtr(this);
       
             /*The equivalent in C# works perfectly fine:*/
            
                /*this.child = child;
                if(child != null) {
                    child.parent = this;
                }*/
            

        }
    }

    const T& Value()    const { return value; }
    T& ValueRef()       const { return value; }
    NodePtr Parent()     const { return parent; }
    NodePtr Child()     const { return child; }
};
template<typename T> std::ostream& operator<<(std::ostream& stream, const Node<T>& node) {
    stream << "{" << node.Value() << "}";
    return stream;
}
int main()
{
    Node<int> n{ 5, std::make_shared<Node<int>>(3) };
    std::cout << n;
}

I can implement this easily without using smart pointers, but I’m trying to learn them so there’s that.

The assertion that is failing: “is_block_type_valid(header->_block_use)”

Image of the assertion error

Any help would be appreciated, thank you.

Answer

There are a few problems. First, if you want to get a shared_ptr from this, you have to inherit from std::enable_shared_from_this:

template<typename T> class Node : std::enable_shared_from_this<Node<T>> {
    // ...

The main problem is that there is a shared_ptr referencing a shared_ptr (the parent to the child, vice-versa). However, shared_ptr are only reference-counted. Take a look at the program below:

#include <iostream>
#include <memory>
struct A;

struct B{
    std::shared_ptr<A> sp;
    ~B(){ std::cout << "B destroyedn"; }
};
struct A{
    std::shared_ptr<B> sp;
    ~A(){ std::cout << "A destroyedn"; }
};

int main(){
    std::shared_ptr<B> b{};
    std::shared_ptr<A> a {b->sp};
    b = a->sp;
}

The output is blank! Here is a link to the above program.

To fix, do two additional things: one, change child->parent = NodePtr(this); to the following:

child->parent = this->weak_from_this();

Also, change the type of parent to std::weak_ptr<Node<T>>.

std::weak_ptr is used with problems like this. It doesn’t influence the reference count of the std::shared_ptr For more information, go here.

P.S. the error about the is_block_type was caused by shared_ptr, probably because you tried to get a shared_ptr from a raw ptr. Read more about std::shared_ptr here.