关于如何在基于动态数组的结构中存储键值对的想法

发布于 2024-10-12 09:17:38 字数 361 浏览 2 评论 0原文

我有一个具有以下属性的动态数组:

  1. 存储键值对结构。
  2. 每当添加条目时重新分配内存 (realloc)。调用构造函数。
  3. 删除很棘手 - 被删除的条目必须从它所在的位置移动到数组的末尾 - 它的内容(键和值)必须与数组中当前的最后一项交换。调用析构函数。重新分配内存以便删除该条目。

现在的问题是我最初通过引用将值存储在条目中。但是,我不能使用 operator= 。但我也不能按值存储。我不想存储指针,因为这会破坏整个目的。目前我看到的唯一选择是在被删除的条目上调用placement new,并从最后一个元素调用复制构造函数。这将使我可以通过引用保留值。有什么建议吗?或者我应该注意的陷阱?

I have a dynamic array that has the following properties:

  1. Stores Key-Value pair structures.
  2. Re-allocates memory whenever an entry is added (realloc). Invoke constructor.
  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

離殇 2024-10-19 09:17:38

我不明白为什么通过指针存储与通过引用存储有什么不同。您获得了能够重新分配的优势,这是您所说的您需要的。

  1. 它们占用相同的大小
  2. 只要容器还活着,您仍然有责任保持引用对象处于活动状态
  3. 有人仍然负责在某个时候销毁引用对象
  4. 您可以对公共 API 隐藏此选择

引用的唯一优点是它不能为空,但没有人会直接访问它。您仍然可以在 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.

  1. They take up the same size
  2. You are still responsible for keeping the referent alive as long as the container is alive
  3. Someone is still responsible for destroying the referent at some point
  4. You can keep this choice hidden from the public API

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文