欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++内存(内存池)管理讲解

程序员文章站 2022-03-09 22:10:02
内存管理的目的:提高速度,降低空间浪费率 减少malloc的使用。(可以先分配一大块,再一点一点的使用) 较少cookie的使用。 #include using n...

内存管理的目的:提高速度,降低空间浪费率

减少malloc的使用。(可以先分配一大块,再一点一点的使用) 较少cookie的使用。

#include 

using namespace std;

class Screen {
public:
    Screen(int x):i(x) {}
    int get() { return i; }

    void* operator new(size_t);
    void operator delete(void*, size_t);

private:
    Screen* next; // 为了去掉cookie
    static Screen* freeStore;
    static const int screenChunk;
private:
    int i;
};

Screen* Screen::freeStore = 0;
const int Screen::screenChunk = 24; // 创建24份,内存池

void* Screen::operator new(size_t size) {

    Screen* p;
    if (!freeStore) {
        std::cout << "operator new" << std::endl;
        //linked list是空的,所有申请一大块
        size_t chunk = screenChunk * size;
        freeStore = p = reinterpret_cast (new char[chunk]);

        //将一大块分割成片,当做linked list串接起来
        for (; p!=&freeStore[screenChunk-1]; ++p) {
            p->next = p + 1;
        }
        p->next = 0;
    }
    p = freeStore;
    freeStore = freeStore->next;
    return p;
}

void Screen::operator delete(void* p, size_t) {
    //将deleted object 插入free list前端
    (static_cast(p))->next = freeStore;
    freeStore = static_cast(p);
}

int main() {
    cout << sizeof(int) << endl;
    cout << sizeof(Screen) << endl;

    size_t const N = 100;
    Screen* p[N];

    for (int i = 0; i < N; ++i) {
        p[i] = new Screen(i);
    }

    //输出前10个指针,比较其间隔,确认其没有cookie
    for (int i = 0; i < 10; ++i) {
        cout << p[i] << endl;
    }

    for (int i = 0; i < N; ++i) {
        delete p[i];
    }
    return 0;
}