【问题标题】:Move semantics c++ singly linked list [closed]移动语义c ++单链表[关闭]
【发布时间】:2020-04-11 01:14:17
【问题描述】:

我一直在学习 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);
}

【问题讨论】:

  • 我认为这个请求的正确渠道是:codereview.stackexchange.com
  • 请您改写您的问题?不清楚你在问什么:你不应该要求一般的“代码审查”或“提示和技巧”。您有什么特别想问的吗?如果是这样,请改写询问。
  • 移动不应该深度复制和删除,它应该只是“窃取”内容。 (此外,您正在泄漏整个原始树。)
  • 评论//Check if objects are of the same type.有误。您正在检查它们是否是同一个对象,这是完全不同的事情。

标签: c++ copy-constructor move-semantics assignment-operator


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多