C++内存管理15 含宏的static分配

使用宏进行简化
C++内存管理15 含宏的static分配_第1张图片
C++内存管理15 含宏的static分配_第2张图片

#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<CHUNK-1;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;
}

// DECLARE_POOL_ALLOC -- used in class definition
//为类内的两个函数写的
#define DECLARE_POOL_ALLOC() \
public: \
    void* operator new(size_t size) { return myAlloc.allocate(size); } \
    void operator delete(void* p) { myAlloc.deallocate(p, 0); } \
protected: \
    static Allocator myAlloc; 

// IMPLEMENT_POOL_ALLOC -- used in class implementation file
//为类外的那一句写的
#define IMPLEMENT_POOL_ALLOC(class_name) \
Allocator class_name::myAlloc;


// in class definition file
class Foo {
   DECLARE_POOL_ALLOC();
public: 
	long L;
	string str;
public:
	Foo(long l) : L(l) {  }   
};
//in class implementation file
IMPLEMENT_POOL_ALLOC(Foo) 


//  in class definition file
class Goo {
   DECLARE_POOL_ALLOC()
public: 
	complex<double> c;
	string str;
public:
	Goo(const complex<double>& x) : c(x) {  }   
};
//in class implementation file
IMPLEMENT_POOL_ALLOC(Goo) 


void test_macros_for_static_allocator()
{
	cout << "\n\n\ntest_macro_for_static_allocator().......... \n";
		
Foo* pF[100];
Goo* pG[100];
 
	cout << "sizeof(Foo)= " << sizeof(Foo) << endl;
	cout << "sizeof(Goo)= " << sizeof(Goo) << endl;	
	
   	for (int i=0; i<23; ++i) {	//23,任意數, 隨意看看結果 
	   	pF[i] = new Foo(i); 
	   	pG[i] = new Goo(complex<double>(i,i)); 	   	
	    cout << pF[i] << ' ' << pF[i]->L << "\t";
	    cout << pG[i] << ' ' << pG[i]->c << "\n";	    
	}
	
   	for (int i=0; i<23; ++i) {
	   	delete pF[i]; 
	   	delete pG[i]; 	   	
	}	
	
}

int main(){
    test_macros_for_static_allocator();
    return 0;
}

运行结果:

C++内存管理15 含宏的static分配_第3张图片
标准库有很多个allocator,其中一个有16个自由链表,是一个全局的allocator针对所有的class。
C++内存管理15 含宏的static分配_第4张图片

以上来自侯捷老师视频仅用于学习。

你可能感兴趣的:(C++内存管理,c++)