系统相关
首页 > 系统相关> > C++小型内存池实现

C++小型内存池实现

作者:互联网

class Foo {
public:
    Foo(int x) : id(x) {}
    int getId() {return id;}
    ~Foo() {}

    void *operator new(size_t sizes) {
        Foo *p;
        if(!freeStore) {
            //linkList is empty
            size_t num = FooNum * sizes;
            freeStore = p = reinterpret_cast<Foo*>(new char [num]);

            while(p != &freeStore[FooNum - 1]) {
                p->next = p + 1;
                p++;
            }
            p->next = 0;
        }

        p = freeStore;
        freeStore = freeStore->next;
        return p;
    }
    void operator delete(void *p,size_t) {
        (static_cast<Foo*>(p))->next = freeStore;
        freeStore = static_cast<Foo*>(p);
    }
private:
    Foo *next;
    int id;
    static int FooNum;
    static Foo *freeStore;
};

int Foo::FooNum = 24;
Foo* Foo::freeStore = 0;

内存池的实现节省了空间和时间。
每次new一个对象都会存在一个cookie,如果连续new多个对象会有很多个cookie从而会浪费内存,内存池的实现则使得cookie变为一个,即只new一次。Foo中有一个int和一个指针(分别都是4字节)所以间隔8字节。
在这里插入图片描述
省的时间在于new底层会调用malloc,则因此减少了调用malloc的次数。精髓在于重载new和delete,此内存池里有一个指针指向下一个对象。

标签:小型,int,C++,next,内存,new,Foo,freeStore
来源: https://blog.csdn.net/mazamu/article/details/120310166