又修改了一下,去掉了指向指针的指针
template <class T1>
class FixSizeMemoryPool
{
public:
FixSizeMemoryPool(T1 *addr, size_t nblocks);
T1* allocate();
void release(T1 *pblk);
private:
union TU{ T1 value; TU * ptrNext; };
TU *m_addr; // Pointer to beginning of memory partition
TU *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 (T1 *), u8"内存块的大小至少要能存一个指针");
m_addr = (TU *)addr;
m_freeList = (TU *)addr;
m_NFree = nblocks;
m_NBlocks = nblocks;
TU *pTU = m_addr; /* Create linked list of free memory blocks */
TU *pBlock = m_addr + 1;
while (--nblocks > 0)
{
pTU->ptrNext = pBlock;
pTU = pBlock;
pBlock ++;
}
pTU->ptrNext = nullptr;
}
template <class T1>
T1* FixSizeMemoryPool<T1>::allocate()
{
TU *pBlock = nullptr;
if (m_NFree > 0)
{
pBlock = m_freeList; /* Yes, point to next free memory block */
m_freeList = pBlock->ptrNext; /* Adjust pointer to new free list */
m_NFree--;
}
return (T1*) pBlock;
}
template <class T1>
void FixSizeMemoryPool<T1>::release(T1 *pblk)
{
TU * pBlock = (TU *) pblk;
pBlock->ptrNext = m_freeList;
m_freeList = pBlock;
m_NFree++;
}
【 在 wjhtingerx 的大作中提到: 】
: 不需要大小动态的,就是固定几个大小,一定数量内存块,可以申请和释放的。
--
FROM 171.88.31.*