内存池02
通过上一节的介绍,你应该能够对内存管理有个大概的了解,上一节提到为了设计内存池增加了一个指针next,但它额为增加了4个字节,这不是我们所需要的。于是对它进行了优化,先看代码和云心结果
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class foo{
public:
struct MyStruct
{
int a;
int b;
};
union
{
MyStruct re;
foo *next;
};
void setData(int x,int y)
{
re.a = x;
re.b = y;
}
void showmsg()
{
cout << re.a << " " << re.b << endl;
}
static void *operator new(size_t size)
{
foo *p;
if (!freestore)
{
size_t nsize = size*ncount;
freestore = p = reinterpret_cast<foo *>(new char[nsize]);
for (int i = 0; i < ncount; i++)
{
p->next = p + 1;
p++;
}
p->next = NULL;
}
p = freestore;
freestore = freestore->next;
return p;
}
static void operator delete(void *p)
{
//将回收的内存放到头节点。
(static_cast<foo *>(p))->next = freestore;
//将第一个内存指向回收的内存
freestore = static_cast<foo *>(p);
}
~foo()
{
cout << "~foo()\n";
}
public:
static const int ncount;
static foo *freestore;
};
const int foo::ncount = 24;
foo *foo::freestore = NULL;
void main()
{
cout << sizeof(foo) << endl;
foo *pfoo[100];
for (int i = 0; i < 100; i++)
{
pfoo[i] = new foo;
pfoo[i]->setData(i + 1, i + 2);
}
for (int i = 80; i < 90;i++)
{
cout << pfoo[i] << " ";
pfoo[i]->showmsg();
}
system("pause");
}
运行结果;
和上一个例子的最大区别就在于将数据部分写在一个结构体中,然后使用了匿名union,这样为了节省next指针的内存空间。因为联合体同时只能存在一个变量。这也叫做嵌入式指针。从运行结果可以看出间隔为8.