C++14 不能调用从唯一指针继承的类的复制构造函数或运算符 =
C++14 can not call copy constructor or operator= of class inheriting from unique pointer
我在调用构造函数/运算符时遇到问题。我有一个类树,它是指向节点的唯一指针。这是我实现移动和复制构造函数/运算符的代码。
template <class Key, class Data>
class Node;
template <class Key, class Data>
class Tree : public unique_ptr<Node<Key, Data>>
{
using unique_ptr<Node<Key, Data>>::unique_ptr;
public:
/*Default empty constructor*/
Tree(){
this->reset();
}
/*Default constructor*/
Tree(const Key& key, const Data& data) : unique_ptr<Node<Key, Data>>(make_unique<Node<Key, Data>>(key, data)) {
}
/*Copy constructor*/
Tree(const unique_ptr<Node<Key, Data>>& tree) : unique_ptr<Node<Key, Data>>(nullptr){
if(tree){
this->reset(new Node<Key, Data>(*tree));
}
}
/*Move constructor: roep de move constructor van unique_ptr op*/
Tree(unique_ptr<Node<Key, Data>>&& tree) : unique_ptr<Node<Key, Data >>(move(tree)) {
}
/*Copy operator*/
Tree<Key, Data>& operator=(const unique_ptr<Node<Key, Data>>& tree) {
if (this != &tree) {
this->reset(make_unique(Tree<Key, Data>(*tree)));
if ((*this)->left != nullptr) {
(*this)->left = tree->left;
}
if ((*this)->right != nullptr) {
(*this)->right = tree->right;
}
}
return *this;
}
/*Move operator*/
Tree<Key, Data>& operator=(unique_ptr<Node<Key, Data >>&& tree) {
if (this != &tree) {
*this = unique_ptr<Key, Data>::operator=(std::move(tree));
}
return *this;
}}
当我尝试使用构造函数或运算符 = 将树 a 复制到树 b 时,我收到一个错误,告诉我运算符已被隐式删除。我知道当您实现移动/复制构造函数/运算符时,默认的不能再使用,您也必须实现所有其他构造函数/运算符。但从我的角度来看,我实现了所有这些。
代码示例
Tree<int, char> tree;
Tree<int, char> copy;
copy = tree;
错误:无法分配类型为"Tree"的对象,因为其复制赋值运算符已被隐式删除
您的"移动构造函数"和"复制赋值运算符"没有正确的签名。它们应该是Tree(Tree&&)
和Tree& operator=(const Tree&)
.
执行copy = tree;
时,不会使用任何函数,但会选择编译器生成的默认赋值运算符。而这恰好被删除(= delete;
),因为基类的副本赋值被删除了。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 复制构造函数、赋值运算符C++
- std::ofstream 作为类成员删除复制构造函数?
- 复制构造函数C++无法正确复制指针
- 关于复制构造函数的一个棘手问题
- 为什么调用复制构造函数而不是移动构造函数?
- 填充上编译器生成的复制构造函数之间的不一致
- C++ 对象指针数组的复制构造函数
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 防止在复制构造函数中隐式调用基构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 具有已删除移动和复制构造函数的类的就地构造
- 复制构造函数隐式转换问题
- 复制构造函数中的递归调用