繁体   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