首页 > 解决方案 > 移动语义 C++ 单链表

问题描述

我一直在学习 C++ 中的移动语义,我想我已经明白了。只是为了确定我想知道是否有人可以给我一些提示,甚至给我一些改进我的代码的建议。谢谢 :)

如果您想知道为什么我不会为此使用二叉树或其他任何东西,我正在将字典实现为分配的链表。

template<class Key, class Item>
Dictionary<Key, Item>::Dictionary(const Dictionary& original)
{
    std::cout << "Copy Constructor Invoked" << std::endl;
    this->root = deepCopy(original.root);

}

template<class Key, class Item>
Dictionary<Key, Item>& Dictionary<Key, Item>::operator=(const Dictionary& original)
{
    //Check if objects are of the same type.
    if (this == &original)
    {
        return *this;
    }
    root = deepCopy(original.root);
    return *this;
}

template<class Key, class Item>
Dictionary<Key, Item>::Dictionary(Dictionary&& original)
{
    std::cout << "Move Constructor" << std::endl;
    this->root = deepCopy(original.root);
    original.root = nullptr;
    deepDelete(original.root);

}

template<class Key, class Item>
Dictionary<Key, Item>& Dictionary<Key, Item>::operator=(Dictionary&& original)
{
    //Check if objects are of the same type.
    if (this == &original)
    {
        return *this;
    }

    std::cout << "Move Operator" << std::endl;

    root = original.root;
    original.root = nullptr;
    deepDelete(original.root);
    return *this;
}

template<class Key, class Item>
inline Dictionary<Key, Item>::~Dictionary()
{
    deepDelete(root);
}

标签: c++copy-constructormove-semanticsassignment-operator

解决方案


移动构造函数通常不应该执行“深度复制”。它应该做一个浅拷贝,然后将原始对象恢复到强制任何类不变量的状态。如果没有不变量,那么单独的浅拷贝就足够了(在这种情况下,隐式生成的移动构造函数可以满足您的需求)。

此外,您将 nullptr 传递给deepDelete,这对我来说毫无意义。

直观地说,一个明智的移动构造函数应该是这样的:

this->root = original.root; // shallow copy
original.root = nullptr;    // enforce class invariant of unique ownership

推荐阅读