关于C++中内存池的探究

发布于 2024-12-27 09:33:28 字数 454 浏览 5 评论 0原文

是否可以创建一个遵循简单逻辑的内存池实现:

1 - 分配 n 字节的内存池。

2 - 使用修改后的 new();不分配内存的函数/运算符仅获取指向内存池开头的指针。这样,对象就可以动态创建,无需任何开销。

3 - 当内存池不足时,它会释放剩余的内存并分配一个新的内存池

4 - 在第一个内存池中创建的对象将根据其大小来获取内存。第一个池中分配的内容与资源不足时返回的内容之间的差异由对象在删除时恢复。

我担心的主要是我不知道如何删除小于分配的内存池,请记住,除了内存池对象末尾剩下的内容之外,还有内存池的操作系统标头这是在池中分配的第一个对象之前。我需要什么方法来确保没有内存泄漏,删除多余的内存池不会删除在其中分配的对象,并且内存池片段的标头被安全删除。

谢谢!

编辑:请注意,目的是让内存由内存池分配并由对象释放,这些对象可能具有不同的生命周期。如果这可能的话......

Is it possible to create a memory pool implementation that follows the simple logic:

1 - Allocate n bytes worth of memory pool.

2 - Use modified new(); function/operator that does not allocate memory only gets a pointer to the beginning of the memory pool. This way objects are created dynamically without overhead.

3 - When the memory pool runs low, it deallocates what is left of it and allocates a new memory pool

4 - the objects created in the first memory pool are left to pick up the memory based on their sizes. The difference of what was allocated in the first pool and what was given back when it ran low is restored by the objects upon their deletion.

My worries are mainly about the fact that I have no idea how to delete the memory pool smaller than it was allocated, KEEPING IN MIND that besides what is left in the end of the memory pool object there is also a OS header for the memory pool that is before the first object, allocated in the pool. What approach do I need to make sure no memory is leaked, that deleting the excess memory pool won't delete objects that are allocated in it and that the header for the memory pool fragment is safely removed.

Thanks!

EDIT: Note that the intent is for memory to be allocated by the memory pool and released by the objects, which may have different lifetime. If this is possible at all...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

狼性发作 2025-01-03 09:33:28

首先,如果您想知道应该搜索什么,这听起来像一个竞技场分配器(如评论中提到的)。

请注意,只有当您打算立即拆除整个东西时,竞技场才真正有用;如果您希望从已删除的对象中回收内存以供重复使用,那么您最终会在竞技场顶部编写自己的堆。如果您只是想让 arena-chunk 保持活动状态,直到最后一个对象被释放,您可以使用引用计数进行管理。

其次,我知道分配内存的唯一常见方法是使用内存映射,以后可以缩小内存而无需移动(如 realloc):这是特定于平台的。

Firstly, this sounds like an arena allocator (as mentioned in the comments), if you want to know what you should be searching for.

Note that arenas are only really useful if you plan to tear down the whole thing at once; if you expect to reclaim memory from deleted objects for re-use, you end up writing your own heap sitting on top of the arena. If you just want to keep the arena-chunk alive until the last object is deallocated, you can manage with a refcount.

Secondly, the only common way I know to allocate memory which you can later shrink without possibly moving (like realloc), is using memory maps: this is platform-specific.

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