简体   繁体   English

C ++中的内存池查询

[英]An inquiry on memory pools in C++

Is it possible to create a memory pool implementation that follows the simple logic: 是否可以创建遵循简单逻辑的内存池实现:

1 - Allocate n bytes worth of memory pool. 1-分配n个字节的内存池。

2 - Use modified new(); 2-使用修改过的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 3-内存不足时,它会释放剩余的内存并分配一个新的内存池

4 - the objects created in the first memory pool are left to pick up the memory based on their sizes. 4-在第一个内存池中创建的对象将保留以根据其大小选择内存。 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. 我担心的主要是我不知道如何删除小于分配的内存池的事实,请记住,除了在内存池对象末尾剩下的内容之外,还有一个用于内存池的OS标头在池中分配的第一个对象之前。 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... 如果这完全有可能...

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. 如果您只想让竞技场块保持活动状态,直到释放最后一个对象,则可以使用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. 其次,我知道的分配内存的唯一通用方法是使用内存映射:您可以在以后缩小该内存而不必移动(例如重新分配),这是特定于平台的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM