簡體   English   中英

使用已刪除的函數std :: unique_ptr

[英]use of a deleted function std::unique_ptr

該錯誤似乎是在函數insert和printTree中。 我知道此錯誤是由unique_ptr無法復制引起的。 但是我認為提供移動和復制語義應該可以幫助我解決它。 我的問題

  1. 我是否使復制和移動構造函數正確?

  2. 如果不。 我應該如何重新設計代碼。 請列出基本錯誤以及糾正方法。

  3. 如何將Node *父級並入班級?

  4. 在這種情況下,關於良好代碼實踐的一些技巧會有所幫助

     // This is implementation of binary search tree. #ifndef BinarySearchTree_H #define BinarySearchTree_H #include <cstdio> #include <functional> #include <utility> #include <vector> #include <iostream> #include <memory> //template declaration template <class ValueType> class BinarySearchTree { struct Node { ValueType value; std::unique_ptr<Node> left; std::unique_ptr<Node> right; //Node *parent=nullptr; // How can I use parent in the class ? Node(){} //Node(const ValueType& value,std::unique_ptr<Node> left,std::unique_ptr<Node> right):value(value),left(left),right(right){} Node (const ValueType& value):value(value),left(nullptr),right(nullptr){} }; std::unique_ptr<Node> root; void insert(const ValueType& value, std::unique_ptr<Node> node) { if(value< node->value) { if(node->left) { insert(value,node->left); } else { std::unique_ptr<Node> left=std::unique_ptr<Node>(new Node(value)); node->left=left; } } else { if(node->right) { insert(value,node->right); } else { std::unique_ptr<Node> right=std::unique_ptr<Node>(new Node(value)); node->right=right; //right->parent=node; } } } void printNode(std::unique_ptr<Node> node) { if(!node) { std::cout<<"No element in the tree\\n"; } else { if(node->left) { std::cout<<node->left->value<<" "; } std::cout<<node->value<<" "; if(node->right) { std::cout<<node->right->value<<" "; } } } public: BinarySearchTree():root(nullptr){} ~BinarySearchTree(){} BinarySearchTree( BinarySearchTree && rhs):root(std::move(rhs.root)){} BinarySearchTree& operator=(BinarySearchTree && rhs ) { root=std::move(rhs.root); return *this; } BinarySearchTree& operator=(const BinarySearchTree & rhs ) { if(this!=&rhs) root.reset(rhs.root); return *this; } void insert(const ValueType& value) { if(root==nullptr) { root=std::unique_ptr<Node>(new Node(value)); } else { insert(value,root); } } // void remove(const ValueTypr& value); void printTree(const BinarySearchTree& tree) { if(tree.root) { if(tree.root->left) { printNode(tree.root->left); } printNode(tree.root); if(tree.root->right) { printNode(tree.root->right); } } else { std::cout<<"tree is empty\\n"; return; } } }; #endif // BinarySearchTree 
  1. 不可以。您不能復制唯一的指針。 您必須確定樹的深層副本是否有意義。
  2. 使用move構造函數和move賦值運算符,而不要使用復制構造函數和復制賦值運算符。
  3. 添加原始指針Node* parent 父母擁有自己的孩子,反之亦然。
  4. 使用std::make_unique() 避免包含不需要的標題。 是否有一個原因printTree()不能在工作this 通常,您可以使用更具可讀性的語法(縮進,空行等)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM