我一直在学习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);
}发布于 2019-12-18 21:22:16
移动构造函数通常不应该执行“深度复制”。它应该进行浅层复制,然后将原始对象恢复到强制执行任何类不变量的状态。如果没有不变量,那么只有一个浅拷贝就足够了(在这种情况下,隐式生成的move构造函数会做您想要做的事情)。
此外,您正在将nullptr传递给deepDelete,这对我来说毫无意义。
直观地说,合理的移动构造函数应该是这样的:
this->root = original.root; // shallow copy
original.root = nullptr; // enforce class invariant of unique ownershiphttps://stackoverflow.com/questions/59392794
复制相似问题