1

I am working on writing an implementation of a Binary Search Tree. I feel very comfortable with shared_ptr, but it took me a while to code it using unique_ptr. I had to care about NOT letting the function have the ownership of the object, and it got me thinking really hard.

Using shared_ptr, I wrote the following code.

#include <iostream>
#include <memory>

template<class T>
class BinarySearchTree{
    struct Node;
    typedef std::shared_ptr<Node> nodePtr;
    struct Node{
        T data;
        nodePtr  left;
        nodePtr  right;
        Node(const T & value):data(value),left(nullptr),right(nullptr){}
    };



    nodePtr root;
    bool insert(nodePtr node);
    void print(const nodePtr) const ;
public:
    BinarySearchTree();
    void insert( const T & node);
    void print()const;
};

template<class T>
BinarySearchTree<T>::BinarySearchTree():root(nullptr){}

template<class T>
void BinarySearchTree<T>::insert(const T & ref)
{
    Node *node = new Node(ref);
    if (root==nullptr)
    {
        root.reset(node);
    }
    else
    {
        nodePtr temp = root;
        nodePtr prev = root;
        while (temp)
        {
            prev = temp;
            if (temp->data < ref)
                temp = temp->right;
            else
                temp = temp->left;
        }
        if (prev->data  < ref)
            prev->right.reset(node);
        else
            prev->left.reset(node);
    }
}

template<class T>
void BinarySearchTree<T>::print()const
{
    print(root);
}

template<class T>
void BinarySearchTree<T>::print(const nodePtr node)const
{
    if (node==nullptr)
        return;
    print(node->left);
    std::cout << node->data<< std::endl;
    print(node->right);
}

int main()
{
    BinarySearchTree<int> bst;
    bst.insert(13);
    bst.insert(3);
    bst.insert(5);
    bst.insert(31);
    bst.print();
    return 0;
}

Now I read it everywhere that using shared_ptr where unique_ptr is sufficient is an overkill (because of obvious reasons), but how do I go about deciding when to use unique_ptr? Like in this case, would you have done it with unique_ptr from the first place?

happy_sisyphus
  • 1,224
  • 1
  • 15
  • 24

0 Answers0