c++ - Why I cannot convert unique_ptr to a raw pointer in assignment? -
when writing simple binary search tree insertion, encountered compilation error in g++ 4.7
error: cannot convert ‘node_ptr {aka std::unique_ptr<node>}’ ‘node*’ in assignment
for line node* n = root.get()
in bst_insert
function. don't understand why?
struct node; typedef std::unique_ptr<node> node_ptr; struct node { node(int k) : key(k) {}; int key; node_ptr left = nullptr; node_ptr right = nullptr; }; void bst_insert(node_ptr& root, node_ptr z) { node* p = nullptr; node* n = root.get(); while (n != nullptr) { p = n; n = z->key < n->key ? n->left : n->right; } if (p == nullptr) root = std::move(z); else if (z->key < p->key) p->left = std::move(z); else p->right = std::move(z); }
n = z->key < n->key ? n->left : n->right;
this line. n->left
, n->right
std::unique_ptr
s , trying assign unique ptr raw pointer. change line to:
n = z->key < n->key ? n->left.get() : n->right.get();
Comments
Post a Comment