我用网上的代码攒了个极简单的内存池。你看看够不够你的用途。没考虑多线程,如果用在多线程上,可以在外面加锁。
template <class T1>
class FixSizeMemoryPool
{
public:
FixSizeMemoryPool(T1 *addr, size_t nblocks);
T1* allocate();
void release(T1 *pblk);
private:
T1 *m_addr; // Pointer to beginning of memory partition
T1 *m_freeList; // Pointer to list of free memory blocks
size_t m_NBlocks; // Total number of blocks in this partition
size_t m_NFree; // Number of memory blocks remaining in this partition
};
template <class T1>
FixSizeMemoryPool<T1>::FixSizeMemoryPool(T1 *addr, size_t nblocks)
{
static_assert (sizeof (T1) >= sizeof (void *), u8"内存块的大小至少要能存一个指针");
m_addr = addr;
m_freeList = addr;
m_NFree = nblocks;
m_NBlocks = nblocks;
T1 **plink = (T1 **)addr; /* Create linked list of free memory blocks */
T1 *pblk = addr + 1;
for (size_t i = 0; i < (nblocks - 1); i++)
{
*plink = (T1 *)pblk;
plink = (T1 **)pblk;
pblk ++;
}
*plink = nullptr;
}
template <class T1>
T1* FixSizeMemoryPool<T1>::allocate()
{
T1 *pblk = nullptr;
if (m_NFree > 0)
{
pblk = m_freeList; /* Yes, point to next free memory block */
m_freeList = *(T1 **)pblk; /* Adjust pointer to new free list */
m_NFree--;
}
return (pblk);
}
template <class T1>
void FixSizeMemoryPool<T1>::release(T1 *pblk)
{
*(T1 **)pblk = m_freeList;
m_freeList = pblk;
m_NFree++;
}
【 在 wjhtingerx 的大作中提到: 】
: 不需要大小动态的,就是固定几个大小,一定数量内存块,可以申请和释放的。
--
FROM 220.166.239.*