此代码可作为商业代码,在使用内存池的场合直接拿来使用,特此记录!
// 分配内存池 嵌入式指针
class allocatorPool
{
public:
//分配
void *allocator(size_t size)
{
obj *tmplink;
if (m_FreePos == nullptr)
{
//分配内存池
size_t i_realsize = i_sTrunkCount * size;
m_FreePos = (obj*)malloc(i_realsize);
tmplink = m_FreePos;
//把内存池链起来
for (int i = 0; i < i_sTrunkCount -1 ; ++i)
{
tmplink->next = (obj*)((char*)tmplink + size);
tmplink = tmplink->next;
}
tmplink->next = nullptr;
}
tmplink = m_FreePos;
m_FreePos = m_FreePos->next;
return tmplink;
}
//释放
void dealallocator(void *head)
{
((obj*)head)->next = m_FreePos;
m_FreePos = (obj*)head;
}
private:
struct obj
{
struct obj *next; //嵌入到类内的指针 此struct不占内内存,所以要求类必须大于4字节
};
obj* m_FreePos = nullptr;
size_t i_sTrunkCount = 5;
};
//对类A使用内存池
class A
{
public:
int m_i;
int m_j;
static allocatorPool alloc;
static void* operator new(size_t size)
{
return alloc.allocator(size);
}
static void operator delete(void *head)
{
alloc.dealallocator(head);
}
};
allocatorPool A::alloc;
int main()
{
A *mypa[100];
for (int i = 0; i < 15; ++i)
{
mypa[i] = new A();
mypa[i]->m_i = 5;
mypa[i]->m_j = 60;
printf("%p\n", mypa[i]);
}
for (int i = 0; i < 15; ++i)
{
delete mypa[i];
}
return 0;
}