对象池的简单实现


ObjectPool.h
 #ifndef ObjectPool_H__
#define ObjectPool_H__

#include <list>
#include <iostream>
using namespace std;

template<class T>
class ObjectPool
{
private:
    list<void *> object_list;
public:
    void* malloc_object()
    {
        cout << "malloc_object" <<endl;
        
        if(!object_list.empty())
        {
            list<void *>::iterator it = object_list.begin();
            void *p = *it;
            object_list.pop_front();
            return p;
        }
        else
        {
            void* p = malloc(sizeof(T));
            return p;
        }
    }

    void free_object(void* p)
    {
        cout << "free_object" <<endl;

        object_list.push_back(p);
    }
};


#define OBJECT_POOL_DECLARE(CLASS_NAME) \
 private: \
    static ObjectPool<CLASS_NAME> m_ObjPool; \
 public: \
    void* operator new(size_t size); \
    void operator delete(void* p);


#define OBJECT_POOL_IMPLEMENT(CLASS_NAME) \
ObjectPool<CLASS_NAME> CLASS_NAME::m_ObjPool; \
void* CLASS_NAME::operator new(size_t size) \
{ \
    return m_ObjPool.malloc_object(); \
} \
void CLASS_NAME::operator delete(void* p) \
{ \
    m_ObjPool.free_object(p); \
}


posted on 2009-04-14 23:35  Eric Xiang  阅读(134)  评论(0编辑  收藏  举报