实例代码:
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
namespace _nmsp1
{
void func()
{
}
}
namespace _nmsp2
{
class A
{
public:
int m_i;
int m_j;
static void *operator new(size_t size);
static void operator delete(void *phead);
static int m_iCout;
static int m_iMallocCount;
private:
A *next;
static A* m_FreePosi;
static int m_sTrunkCout;
};
int A::m_iCout = 0;
int A::m_iMallocCount = 0;
A *A::m_FreePosi = nullptr;
int A::m_sTrunkCout = 5;
void *A::operator new(size_t size)
{
#ifdef MYMEMPOOL
A *ppoint = (A*)malloc(size);
return ppoint;
#endif
A *tmplink;
if (m_FreePosi == nullptr)
{
size_t realsize = m_sTrunkCout * size;
m_FreePosi = reinterpret_cast<A*>(new char[realsize]);
tmplink = m_FreePosi;
for (; tmplink != &m_FreePosi[m_sTrunkCout - 1]; ++tmplink)
{
tmplink->next = tmplink + 1;
}
tmplink->next = nullptr;
++m_iMallocCount;
}
tmplink = m_FreePosi;
m_FreePosi = m_FreePosi->next;
++m_iCout;
return tmplink;
}
void A::operator delete(void *phead)
{
#ifdef MYMEMPOOL
free(phead);
return;
#endif
(static_cast<A*>(phead))->next = m_FreePosi;
m_FreePosi = static_cast<A*>(phead);
}
void func()
{
clock_t start, end;
start = clock();
for (int i = 0; i < 15; i++)
{
A *pa = new A();
printf("%p\n", pa);
}
end = clock();
cout << "申请分配内存的次数为:" << A::m_iCout << " 实际malloc的次数为:" << A::m_iMallocCount << " 用时(毫秒): " << end - start << endl;
}
}
namespace _nmsp3
{
class TestEP
{
public:
int m_i;
int m_j;
public:
struct obj
{
struct obj *next;
};
};
void func()
{
TestEP mytest;
cout << sizeof(mytest) << endl;
TestEP::obj *ptemp;
ptemp = (TestEP::obj *)&mytest;
cout << sizeof(ptemp->next) << endl;
cout << sizeof(TestEP::obj) << endl;
ptemp->next = nullptr;
}
}
namespace _nmsp4
{
class myallocator
{
public:
void *allocate(size_t size)
{
obj *tmplink;
if (m_FreePosi == nullptr)
{
size_t realsize = m_sTrunkCout * size;
m_FreePosi = (obj *)malloc(realsize);
tmplink = m_FreePosi;
for (int i = 0; i < m_sTrunkCout - 1; ++i)
{
tmplink->next = (obj *)((char *)tmplink + size);
tmplink = tmplink->next;
}
tmplink->next = nullptr;
}
tmplink = m_FreePosi;
m_FreePosi = m_FreePosi->next;
return tmplink;
}
void deallocate(void *phead)
{
((obj *)phead)->next = m_FreePosi;
m_FreePosi = (obj *)phead;
}
private:
struct obj
{
struct obj *next;
};
int m_sTrunkCout = 5;
obj* m_FreePosi = nullptr;
};
#define DECLARE_POOL_ALLOC()\
public:\
static myallocator myalloc; \
static void *operator new(size_t size)\
{\
return myalloc.allocate(size); \
}\
static void operator delete(void *phead)\
{\
return myalloc.deallocate(phead); \
}\
#define IMPLEMENT_POOL_ALLOC(classname)\
myallocator classname::myalloc;
class A
{
DECLARE_POOL_ALLOC()
public:
int m_i;
int m_j;
};
IMPLEMENT_POOL_ALLOC(A)
void func()
{
A *mypa[100];
for (int i = 0; i < 15; ++i)
{
mypa[i] = new A();
mypa[i]->m_i = 12;
mypa[i]->m_j = 15;
printf("%p\n", mypa[i]);
}
for (int i = 0; i < 15; ++i)
{
delete mypa[i];
}
}
}
int main()
{
_nmsp4::func();
return 1;
}