C++ 内存管理03-内存池03(自己写一个allocator)

通过上节的介绍已经改进了内存设计第一版的缺点,但是依然有一个问题,那就是,我们是学面向对象的,不可能每建立一个类,就都写一个内存管理,做重复的动作,那就太没意思了,于是就想着自己封装一个内存管理的工具,专门用来做内存管理。代码如下:

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;
	static allocatorex myallocate;

public:
	
	Foo(int x, int y)
	{
		allocatorex myallocate;
		a = x;
		b = y;
	}
	void showMsg()
	{
		cout << a << "  " << b << endl;
	}
	static void *operator new(size_t size)
	{
		return myallocate.allocate(size);
	}

	static void  operator delete(void *p, size_t size)
	{
		myallocate.deallocate(p, size);
	}
};
allocatorex Foo::myallocate;

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");
}

运行结果:
C++ 内存管理03-内存池03(自己写一个allocator)_第1张图片
运行结果可以看出每五个之间内存间隔为8,得到了自己想要的。

你可能感兴趣的:(内存管理)