类内分配空间效果不错但是每个不同的类要使用的话都要在类内写这个相似的分配操作,没有必要,所以用静态分配。
就是把分配动作抽取出来放到一个class里面。
其他类要使用,只需要按如下这么写。
每个类里面都有一个allocator是专门为Foo类或者Goo类来服务的,allocator里面有一个指针指向一条链表,链表里面划分的每一个区块就是Foo类或者Goo类的大小。全部交给allocator管理。
#include#include #include #include #include #include #include using namespace std; class Allocator{ private: struct obj{ struct obj* next;//embedded pointer }; public: void* allocate(size_t); void deallocate(void*,size_t); private: obj* freeStore = nullptr; const int CHUNK=5;//一次5块小一些方便观察 }; void* Allocator::allocate(size_t size){ obj* p; if(!freeStore){ //链表为空 size_t chunk=CHUNK*size; freeStore=p= (obj*)malloc(chunk); //切割 for(int i=0;i p->next=(obj*)((char*)p+size);//转为char*四个字节这样可以进行加操作 p=p->next; } p->next=nullptr;//last } p=freeStore;//头部给p freeStore=freeStore->next;//freeStore是chunk大小,所以next直接指向传回操作后剩下的第一块 return p; } void Allocator::deallocate(void* p,size_t size){ ((obj*)p)->next=freeStore; freeStore=(obj*)p; } class Foo { public: long L; string str; static Allocator myAlloc; public: Foo(long l) : L(l) { } static void* operator new(size_t size) { return myAlloc.allocate(size); } static void operator delete(void* pdead, size_t size) { return myAlloc.deallocate(pdead, size); } }; Allocator Foo::myAlloc; class Goo { public: complex c; string str; static Allocator myAlloc; public: Goo(const complex & x) : c(x) { } static void* operator new(size_t size) { return myAlloc.allocate(size); } static void operator delete(void* pdead, size_t size) { return myAlloc.deallocate(pdead, size); } }; Allocator Goo::myAlloc; void test_static_allocator_3(){ cout << "nnntest_static_allocator().......... n"; { Foo* p[100]; cout << "sizeof(Foo)= " << sizeof(Foo) << endl; for (int i=0; i<23; ++i) { //23,任意數, 隨意看看結果 p[i] = new Foo(i); cout << p[i] << ' ' << p[i]->L << endl; } //Foo::myAlloc.check(); for (int i=0; i<23; ++i) { delete p[i]; } //Foo::myAlloc.check(); } { Goo* p[100]; cout << "sizeof(Goo)= " << sizeof(Goo) << endl; for (int i=0; i<17; ++i) { //17,任意數, 隨意看看結果 p[i] = new Goo(complex (i,i)); cout << p[i] << ' ' << p[i]->c << endl; } //Goo::myAlloc.check(); for (int i=0; i<17; ++i) { delete p[i]; } //Goo::myAlloc.check(); } } int main(){ test_static_allocator_3(); return 0; }
图中看出5个5个内部是相邻的,外部是分离的。
以上来自侯捷老师视频仅用于学习。



