Search code examples
c++objectbinary-search-treemoveunique-ptr

access to an object member passed by unique_ptr


I wrote the following code to check if a node is in the BST:

bool BST_Node :: BST_Find(unique_ptr<BST_Node> root, int key){ 
    if(!root || root->key == INT_MIN) return false;
    if(root->key == key) return true;
    else if(key < root->key) BST_Find(move(root->left), key);
    else BST_Find(move(root->right), key);
} 

root parameter is passed using move(bst) where bst in an unique_ptr. The problem is when it tries to read root->key: even if the key is present in the tree, this method returns false. I've tried to use the debugger and root can not be accessed.

Here is the code that uses this method:

auto bst = make_unique<BST_Node>();
for(int i=0; i<n; i++){
    key = rand();
    if(!bst->BST_Find(move(bst), key)) {
        bst->BST_Insert(move(bst), key, "");
    }
}

Solution

  • Try this

    bool BST_Node :: BST_Find(unique_ptr<BST_Node> const &root, int key){ 
        if(!root || root->key == INT_MIN) return false;
        if(root->key == key) return true;
        else if(key < root->key) return BST_Find(root->left, key);
        else return BST_Find(root->right, key);
    } 
    
    BST_Find(bst, 42) // no move