如果你熟悉MFC,你肯定见过下面的语句:
以上是图↑
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#define DECLARE_POOL_ALLOC() \
public: \
static void *operator new(size_t size) \
{\
return myallocate.allocate(size); \
} \
\
static void operator delete(void *p, size_t size) \
{\
myallocate.deallocate(p, size);\
}\
protected:\
static allocatorex myallocate;
#define OUT_INIT_POOL_ALLOC(class_name)\
allocatorex class_name::myallocate;
class allocatorex{
private:
struct obj
{
struct obj *next;
};
public:
void *allocate(size_t size)
{
obj *p;
if (!freestore)
{
size_t chunk = CHUNK * size;
freestore = p = (obj *)malloc(chunk);
cout << "---------------------\n";
cout << freestore << endl;
cout << "---------------------\n";
for (int i = 0; i < CHUNK; i++)
{
p->next = (obj *)((char *)p + size);
p = p->next;
}
p->next = NULL;
}
p = freestore;
freestore = freestore->next;
return p;
}
void deallocate(void *p, size_t size)
{
obj *temp = (obj *)p;
temp->next = freestore;
freestore = temp;
}
obj *freestore = nullptr;
const int CHUNK = 5;
};
class Foo{
private:
int a;
int b;
public:
DECLARE_POOL_ALLOC()
public:
Foo(int x, int y)
{
allocatorex myallocate;
a = x;
b = y;
}
void showMsg()
{
cout << a << " " << b << endl;
}
};
OUT_INIT_POOL_ALLOC(Foo);
void main()
{
cout << "sizeof(Foo):" << sizeof(Foo) << endl;
Foo *Afoo[20];
for (int i = 0; i < 20; i++)
{
Afoo[i] = new Foo(i, i + 1);
}
for (int i = 0; i < 20; i++)
{
cout << Afoo[i] << " ";
Afoo[i]->showMsg();
}
for (int i = 0; i < 20; i++)
{
delete(Afoo[i]);
}
system("pause");
}
运行结果: