using namespace std;
//对象池:
template<class _Ty>
class ObjectPool
{
private:
enum { nPoolSize = 4};
protected:
struct _Node
{
_Node* next;
};
_Node* front;
_Node* rear;
void ReFillPool() //填充对象池
{
int total = sizeof(_Node) + sizeof(_Ty);
//在内存中构建四个对象,并把这四个对象初始化好,用的时候直接从对象池中拿
for (int i = 0; i < nPoolSize; ++i)
{
_Node* s = (_Node*)malloc(total);
s->next = nullptr;
new(s + 1) _Ty();//通过定位new在结点s的对象部分构建一个对象
rear->next = s;
rear = s;
}
}
void InitPool() //初始化对象池
{
_Node* s = (_Node*)malloc(sizeof(_Node));
s->next = nullptr;
front = rear = s;
ReFillPool();//填充对象池
}
void Clear() //清除对象池
{
_Node* p = nullptr;
while (front->next != nullptr)
{
p = front->next;
front->next = p->next;
free(p);
}
free(front);
front = rear = nullptr;
}
ObjectPool(const ObjectPool&) = delete;
ObjectPool& operator=(const ObjectPool&) = delete;
public:
ObjectPool() :front(nullptr), rear(nullptr)
{
InitPool();
}
~ObjectPool()
{
Clear();
}
_Ty* allocObjMemory()//从线程池获取一个对象
{
if (front = rear)
{
ReFillPool();
}
_Node* s = front->next;
front->next = s->next;
if (s == rear)
{
rear = front;
}
return (_Ty*)((char*)s + sizeof(_Node));//这里加了sizeof(_Node)主要是返回一个线程,并不需要返回next指针
}
void freeObjMemory(void* q)//释放一个对象并将这个对象还给内存池
{
_Node* p = (_Node*)((char*)q - sizeof(_Node));
p->next = nullptr;
rear->next = p;
rear = p;
}
};
//通过ObjectPoolBase对象的函数从对象池中获取对象以及将对象还给池子
template<class _Ty>
class ObjectPoolBase//单例模式
{
public:
void* operator new(size_t size)
{
return objpool.allocObjMemory();
}
void operator delete(void* p)
{
objpool.freeObjMemory(p);
}
_Ty* GetObject()
{
return objpool.allocObjMemory();
}
void RetObject(_Ty* p)
{
objpool.freeObjMemory(p);
}
static ObjectPoolBase<_Ty>& instance()
{
static ObjectPoolBase<_Ty> objbase;
return objbase;
}
private:
using ClassTypePool = ObjectPool<_Ty>;
ClassTypePool objpool;
};
//创建一个Point类
class Point
{
private:
float _x;
float _y;
public:
Point(float x = 0.0f, float y = 0.0f) :_x(x), _y(y) {}
Point(const Point&) = default;
Point& operator=(const Point&) = default;
~Point() {}
public:
void* operator new(size_t) = delete;
void operator delete(void*) = delete;
};
int main()
{
ObjectPoolBase<Point>& pointpool = ObjectPoolBase<Point>::instance();
Point* ap = pointpool.GetObject();
}
简单对象池
于 2023-09-11 21:01:14 首次发布