samedi 20 février 2021

Why does the below C++ code not compile when using make_shared in insert function of a Binary search tree

The below code does not compile with an error which is not very clear. And If I make changes to remove the compile error then it crashes in the insert function. Would you please let me know what is going wrong here. Also is it not a good idea/good practice to use shared_pointers while making your own container.

'''
//                 generic binary search tree

#include <queue>
#include <stack>
#include <iostream>
#include <memory>
#include <stack>
#include <queue>

using namespace std;

template<typename T>
class BSTNode {
public:
    BSTNode() {
        left = right = nullptr;
    }
    BSTNode(const T& e, shared_ptr<BSTNode <T> > l = nullptr, shared_ptr<BSTNode <T> > r = nullptr) {
        el = e; left = l; right = r;
    }
    T el;
    shared_ptr<BSTNode <T> > left = make_shared<BSTNode <T> >();
    shared_ptr<BSTNode <T> > right = make_shared<BSTNode <T> >();

    ~BSTNode()
    {
      cout<<"~BSTNode"<<endl;
    }
};

template<class T>
class BST {
public:
    BST() {
        root = nullptr;
    }
    ~BST() {
        cout<<"~BST"<<endl;
    }
    void insert(const T);
protected:
    shared_ptr<BSTNode<T> > root;
};

template<class T>
void BST<T>::insert(const T el) {
    shared_ptr<BSTNode<T>> p = root, prev = nullptr;
    while (p != nullptr) {  // find a place for inserting new node;
        prev = p;
        if (el < p->el)
             p = p->left;
        else p = p->right;
    }
    if (root == nullptr)    // tree is empty;
    {
      //It is crashing here.
      root = make_shared<BSTNode<T> >(new BSTNode<T>(el));
    }
    else if (el < prev->el)
         prev->left  = make_shared<BSTNode<T> >(el);
    else prev->right = make_shared<BSTNode<T> >(el);
}

//In main function:
    BST<int> obj1;
    obj1.insert(12);
'''

Aucun commentaire:

Enregistrer un commentaire