samedi 25 avril 2015

Why I cannot convert unique_ptr to a raw pointer in assigment?

When writing a simple binary search tree insertion, I encountered a compilation error in g++ 4.7

error: cannot convert ‘node_ptr {aka std::unique_ptr<node>}’ to ‘node*’ in assignment

for the line node* n = root.get() in bst_insert function. I 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);
}

Aucun commentaire:

Enregistrer un commentaire