歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

C++通過list和template實現簡單的對象池

通過重載new和delete實現簡單的對象池

一個簡單的實現【編輯環境:Linux+Vi,編譯環境:G++】:

C++語言:

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

template<class T>
class object_pool
{
    list<void *> data_list;
public:
    void* malloc_data()
    {
        if(!data_list.empty())
        {
            list<void *>::iterator it = data_list.begin();
            void *p = *it;
            data_list.pop_front();
            return p;
        }
        else
        {
            void* p = malloc(sizeof(T));
            return p;
        }
    }

    void free_data(void* p)
    {
        data_list.push_back(p);
    }
};

class A
{
public:
    int value;
    A(int a):value(a){cout<<"A("<<a<<") called"<<endl;}
    ~A() {cout<<"~A("<<value<<") called"<<endl;}

    static object_pool<A> pool_;
    void* operator new (size_t size)
    {
        return pool_.malloc_data();
    }

    void operator delete(void* p)
    {
        pool_.free_data(p);
    }

};

object_pool<A> A::pool_;

void main()

    A* a1=new A(1);    A* a2=new A(2);
    delete a1;
    delete a2;
}

運行結果:

Copyright © Linux教程網 All Rights Reserved