栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

使用宏进行简化

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

// 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 c;
	string str;
public:
	Goo(const complex& x) : c(x) {  }   
};
//in class implementation file
IMPLEMENT_POOL_ALLOC(Goo) 


void test_macros_for_static_allocator()
{
	cout << "nnntest_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(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;
}

运行结果:


标准库有很多个allocator,其中一个有16个自由链表,是一个全局的allocator针对所有的class。

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/994240.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号