关于如何在基于动态数组的结构中存储键值对的想法
我有一个具有以下属性的动态数组:
- 存储键值对结构。
- 每当添加条目时重新分配内存 (realloc)。调用构造函数。
- 删除很棘手 - 被删除的条目必须从它所在的位置移动到数组的末尾 - 它的内容(键和值)必须与数组中当前的最后一项交换。调用析构函数。重新分配内存以便删除该条目。
现在的问题是我最初通过引用将值存储在条目中。但是,我不能使用 operator=
。但我也不能按值存储。我不想存储指针,因为这会破坏整个目的。目前我看到的唯一选择是在被删除的条目上调用placement new,并从最后一个元素调用复制构造函数。这将使我可以通过引用保留值。有什么建议吗?或者我应该注意的陷阱?
I have a dynamic array that has the following properties:
- Stores Key-Value pair structures.
- Re-allocates memory whenever an entry is added (realloc). Invoke constructor.
- Deletion is tricky - The entry getting deleted has to be moved from wherever it is to the end of the array - It's contents (The Key and the Value) have to be swapped with the current last item in the array. Invoke destructor. Re-allocate memory so that the entry is deleted.
Now the problem is I originally stored the Value by reference in the Entry. But, I can't use operator=
then. But I can't store by value either. And I don't want to store pointers because that would defeat the whole purpose. The only option left I see at the moment is to invoke placement new on the entry getting deleted and invoke copy constructor on it from the last element. This would let me keep the Value by reference. Any advice? Or pitfalls I should look out for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不明白为什么通过指针存储与通过引用存储有什么不同。您获得了能够重新分配的优势,这是您所说的您需要的。
引用的唯一优点是它不能为空,但没有人会直接访问它。您仍然可以在 API 中使用引用,因此不能传入 null。
I don't understand why storing by pointers is any different than storing by reference. You get the advantage of being able to reassign, which you say you need.
The only advantage of the reference is that it can't be null, but no one is going to access it directly. You can still use references in the API, so nulls can't be passed in.