【发布时间】: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