c++ - 移动语义 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);
}
解决方案
移动构造函数通常不应该执行“深度复制”。它应该做一个浅拷贝,然后将原始对象恢复到强制任何类不变量的状态。如果没有不变量,那么单独的浅拷贝就足够了(在这种情况下,隐式生成的移动构造函数可以满足您的需求)。
此外,您将 nullptr 传递给deepDelete
,这对我来说毫无意义。
直观地说,一个明智的移动构造函数应该是这样的:
this->root = original.root; // shallow copy
original.root = nullptr; // enforce class invariant of unique ownership
推荐阅读
- visual-studio-code - VSCode:在定义的文本之间切换
- arrays - 用 3 个参数减少调用,中间有一个奇怪的参数
- python - 将模块文件夹名而不是文件名添加到 Tortoise ORM config_file
- html - 如何使用 Bootstrap(我猜)让 iframe 填充剩余屏幕区域的宽度和高度?
- python - Kubernetes 集群中使用 Python 套接字的服务器-客户端连接
- c# - ASP.NET Core - IServiceProvider 何时处置?
- docker - 在 Container-Optimized OS 中保存持久性可执行文件的位置
- python - 计数符号更改
- sql - 对于类目录应用程序,如何避免使用多个多对多联结的多个 SQL 联结
- c# - 如何修复 Visual Studio 2022 警告 CA1416“所有平台均可访问的呼叫站点”但“仅支持:'windows'”?