原理就是一个内存池内部拥有的空间为POOL_SIZE个自己。
#include<iostream>using namespace std;class DemoClass{
public:DemoClass() = default;DemoClass(int i):data(i){}static void * operator new(size_t size);static void operator delete(void * p);virtual ~DemoClass(){}
private:DemoClass* next;int data;static DemoClass* freeMemeHeader; // 保存的是一个内存,但是表示成自己的地址指针static const size_t POOL_SIZE;
};DemoClass* DemoClass::freeMemeHeader = nullptr;
const size_t DemoClass::POOL_SIZE = 24; // 设定内存池能够容纳24个Democlassvoid* DemoClass::operator new(size_t size){DemoClass* p;if(!freeMemeHeader){size_t pool_mem_bytes = size * POOL_SIZE; //freeMemeHeader = reinterpret_cast<DemoClass*>(new char[pool_mem_bytes]);cout<<"Info: 向操作系统申请了"<<pool_mem_bytes<<"字节的内存。"<<endl;for(int i=0;i<POOL_SIZE-1;i++){// 将内存池中的pool_size小块长连起来freeMemeHeader[i].next = &freeMemeHeader[i+1];}freeMemeHeader[POOL_SIZE-1].next = nullptr;}p = freeMemeHeader;// 取出内存池链表的头部,分配给要实例化的对象cout<<"info: 从内存池中获取了"<<size<<"字节的内存"<<endl;freeMemeHeader = freeMemeHeader->next;p->next = nullptr;return p;
}void DemoClass::operator delete(void * p){DemoClass* temp = (DemoClass*) p;temp->next = freeMemeHeader;freeMemeHeader = temp;
}int main(int argc, char* argv[]){cout << "sizeof(DemoClass):" << sizeof(DemoClass) << endl;size_t N = 32;DemoClass* demos[N];for(int i = 0; i < N; ++i){demos[i] = new DemoClass(i);cout << "address of the ith demo:" << demos[i] << endl;cout << endl;}for(int i=0;i<N;i++){delete demos[i];}return 0;
}