以下是一个简单的内存池实现方法:
- #include<iostream>
- #include<cstring>
- #include<cstddef>
- #include<new>
- using namespace std;
- const int maxnames=5;
- class names
- {
- char name[25];
- static char names::pool[];
- static bool names::inuse[maxnames];
- public:
- names(char* s)
- {strncpy(name,s,sizeof(name));}
- void* operator new(size_t) throw(bad_alloc);
- void operator delete(void*) throw();
- void display()const
- {cout<<name<<endl;}
- };
- //简单的内存池处理确定数量的names
- char names::pool[maxnames*sizeof(names)];
- bool names::inuse[maxnames];
- void* names::operator new(size_t) throw(bad_alloc)
- {
- for(int p=0;p<maxnames;p++)
- {
- if(!inuse[p])
- {
- inuse[p]=true;
- return pool+p*sizeof(names);
- }
- }
- throw bad_alloc();
- }
- void names::operator delete(void* p) throw()
- {
- if(p!=0)
- inuse[((char* )p-pool)/sizeof(names)]=false;
- }
- int main()
- {
- names* nm[maxnames];
- int i;
- for(i=0;i<maxnames;i++)
- {
- cout<<endl<<"enter name #"
- <<i+1<<":";
- char name[25];
- cin>>name;
- nm[i]=new names(name);
- }
- for(i=0;i<maxnames;i++)
- {
- nm[i]->display();
- delete nm[i];
- }
- system("pause");
- return 0;
- }
如果要在内存池中包含自定义的类对象,需要重载类的new运算符,相关方法参见《new和delete运算符重载》