C++14 不能调用从唯一指针继承的类的复制构造函数或运算符 =

C++14 can not call copy constructor or operator= of class inheriting from unique pointer

本文关键字:复制 构造函数 运算符 继承 调用 不能 唯一 指针 C++14      更新时间:2023-10-16

我在调用构造函数/运算符时遇到问题。我有一个类树,它是指向节点的唯一指针。这是我实现移动和复制构造函数/运算符的代码。

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;),因为基类的副本赋值被删除了。