访问 unique_ptr 传递的对象成员
access to an object member passed by unique_ptr
我写了下面的代码来检查一个节点是否在 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 参数使用 move(bst)
传递,其中 bst 在 unique_ptr 中。
问题是当它尝试读取 root->key
时:即使密钥存在于树中,此方法 returns 也是错误的。
我已尝试使用调试器,但无法访问 root。
下面是使用该方法的代码:
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, "");
}
}
试试这个
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
我写了下面的代码来检查一个节点是否在 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 参数使用 move(bst)
传递,其中 bst 在 unique_ptr 中。
问题是当它尝试读取 root->key
时:即使密钥存在于树中,此方法 returns 也是错误的。
我已尝试使用调试器,但无法访问 root。
下面是使用该方法的代码:
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, "");
}
}
试试这个
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