嵌入式指针(allocator3)

 3 版本分开了分配器于具体对象的实现 使用者不必关心allocaotr的具体实现过程

#pragma once
#include
namespace my_alloctor3 {
	class allocator
	{
	public:
		void* allocate(size_t );
		void deallocate(void* , size_t );
	private:
		struct obj {
			struct obj* next;
		};
	private:
		const int BLOCK_SIZE = 5;
		obj* freeStore = nullptr;
	};

	void* allocator::allocate(size_t size)
	{
		obj* p;
		if(!freeStore)
		{
			size_t chunk = size * BLOCK_SIZE;
			freeStore = p =
				(obj*)malloc(chunk);

			for (int i = 0; i < BLOCK_SIZE - 1; ++i)
			{
				p->next = (obj*)((char*)p+size);
				p = p->next;
			}
			p->next = nullptr;
		}
		p = freeStore;
		freeStore = freeStore->next;
		return p;
	}
	void allocator::deallocate(void* pdead, size_t size)
	{
		((obj*)pdead)->next = freeStore;
		freeStore = (obj*)pdead;
	}
}

主函数以及自定义类实现

#include"allocator3.h"
#include
using namespace std;

class A
{
public:
	long L;
	char c;
	int i = 0;
	static my_alloctor3::allocator my_Alloc;
public:
	A(int a):i(a){}
	static void * operator new(size_t size)
	{
		return my_Alloc.allocate(size);
	}
	static void operator delete(void* pdead, size_t size)
	{
		return my_Alloc.deallocate(pdead, size);
	}
};
my_alloctor3::allocator A::my_Alloc;
int main()
{
	A* p[100];
	cout << sizeof(A) << endl;
	for (int i = 0; i < 23; i++)
	{
		p[i] = new A(i);
		cout << p[i]->i << " "<< p[i] << endl;
	}
	for (int i = 0; i < 23; i++)
		delete p[i];
	return 0;
}

你可能感兴趣的:(c++语言,c++)